我是 mongo 的新手,在处理引用关系并在 .net core 中对其进行建模时,我正在寻找一些有关最佳实践的指导。
是的,这就是通常的“加入 mongodb??”问题。但我还没有找到一个好的答案。
为了简单起见,假设我有一个简单的 API,正在使用控制器构建来管理用户和帐户。
在 mongo 中有两个集合,帐户和用户。用户属于其父帐户。在这种情况下,我不想采用嵌入文档路径,因此每个用户文档中都会有一个 AccountID,用于将用户链接回其父帐户。
我当前在 .net 中的实体是:
public class User
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
[BsonElement("firstName")]
public string FirstName { get; set; }
[BsonElement("lastName")]
public string LastName { get; set; }
[BsonElement("email")]
public string Email { get; set; }
[BsonElement("status")]
public string Status { get; set; }
[BsonElement("type")]
public string Type { get; set; }
[BsonElement("createdDateTime")]
public DateTime CreatedDateTime { get; set; }
[BsonElement("modifiedDateTime")]
public DateTime ModifiedDateTime { get; set; }
[BsonRepresentation(BsonType.ObjectId)]
[BsonElement("accountId")]
public string AccountId { get; set; }
}
public class Account
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
[BsonElement("name")]
public string Name { get; set; }
[BsonElement("status")]
public string Status { get; set; }
[BsonElement("type")]
public string Type { get; set; }
[BsonElement("createdDateTime")]
public DateTime CreatedDateTime { get; set; }
[BsonElement("modifiedDateTime")]
public DateTime ModifiedDateTime { get; set; }
}
然后使用控制器中的 AutoMapper 将它们映射到模型
public class UserModel
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string Email { get; set; }
[Required]
public string Status { get; set; }
[Required]
public string Type { get; set; }
[Required]
public DateTime CreatedDateTime { get; set; }
[Required]
public DateTime ModifiedDateTime { get; set; }
[Required]
public string AccountId { get; set; }
}
public class AccountModel
{
[Required]
public string Name { get; set; }
[Required]
public string Status { get; set; }
[Required]
public string Type { get; set; }
[Required]
public DateTime CreatedDateTime { get; set; }
[Required]
public DateTime ModifiedDateTime { get; set; }
}
以及使用映射器的控制器方法的示例:
[HttpGet]
public async Task<ActionResult<List<AccountModel>>> Get()
{
try
{
var results = await _repository.Get();
return _mapper.Map < List < AccountModel >>(results);
}
catch (Exception ex)
{
return this.StatusCode(StatusCodes.Status500InternalServerError, "Database Failure");
}
}
一切都很好。我可以调用控制器方法,获取数据,并将其从实体映射到模型,然后从控制器方法返回。
问题是这样的:我想返回带有帐户信息的用户数据(例如:帐户名称)。所以只是一个简单的加入。
我想我已经掌握了如何使用本文中概述的方法之一进行连接本身answer https://stackoverflow.com/questions/50530363/aggregate-lookup-with-c-sharp。但我的问题是,是否有关于如何设置我的实体和模型以使存储尽可能干净的最佳实践?
我正在考虑向用户实体添加一个属性来存储相关帐户。用 [BsonIgnore] 属性标记,以便它远离数据库。
[BsonIgnore]
public Account Account { get; set; }
该物业
[BsonRepresentation(BsonType.ObjectId)]
[BsonElement("accountId")]
public string AccountId { get; set; }
仍保留在用户实体中,因此引用被保留。
然后,用户模型可以具有如下属性
public string AccountName { get; set; }
他们使用映射器进行填充。
当您想要引用相关对象而不是嵌入它们时,这是设置它的最佳方法吗?我在这里缺少一些陷阱吗?