我们创建了一个模型,该模型具有多个作为集合的多对多导航属性。
public class Shop
{
public Shop()
{
Owners = new HashSet<ShopOwner>();
}
public ShopOwner Creator { get; set; }
public int Id { get; set; }
[Index("IX_Name", IsUnique = true)]
[Required]
[StringLength(100, MinimumLength = 1, ErrorMessage = "Shop name cannot be empty")]
public string Name { get; set; }
public virtual ICollection<ShopOwner> Owners { get; set; }
public virtual ICollection<ShopOwner> Partners { get; set; }
}
此外,
public class ShopOwner : IdentityUser
{
public ShopOwner()
{
Shops = new HashSet<Shop>();
}
public string FirstName { get; set; }
public string LastName { get; set; }
public string PreferredName { get; set; }
public virtual ICollection<Shop> Shops { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ShopOwner> manager)
{
ClaimsIdentity userIdentity =
await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
return userIdentity;
}
}
我们像这样将所有者添加到商店:
Shop shop = context.Shops.Find(shopId);
ShopOwner owner = userManager.FindById(User.Identity.GetUserId());
shop.Owners.Add(owner);
owner.Shops.Add(shop);
context.SaveChanges();
我们遇到的问题是,将所有者添加到商店的所有者会使该用户的所有者对象成为该商店所有者中的唯一所有者。它不像一个集合,当我们使用 SQL Server Management Studio 查看数据库时,我们看到一个名为 ShopOwner_Id
的列,但没有表或商店与所有者之间的关系。
知道为什么这个集合属性会这样吗?
最佳答案
我不太确定这里的问题来源。但仍然认为用 EF 编写多少对多的关系。因此,您可能会遇到问题并最终解决它。
当您在两个 POCO 模型中定义通用集合时,它在 EF 中被视为多对多关系,如上述情况。
在后端 EF 将生成第三个表,用于存储具有以下约定的多对多关系。
TableATableB
因此,根据这个约定,您应该有一个名为 ShopShopOwner 或 ShopOwnerShop 的表(前提是您没有在任何地方覆盖任何约定和表名。)。
它的定义如下所示
ShopId ShopOwnerId
1 2
1 3
2 5
下面的语句将在上表中产生一行。
shop.Owners.Add(owner);
因此您不再需要执行以下操作。
owner.Shops.Add(shop);
第二个语句可能导致违反 ShopShopOwner
表中的主键。因为 EF 引入的第三个表将具有组合键(ShopId 和 ShopOwnerId)。
关于c# - 导航属性(集合)一次只存储一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28313082/