Entity framework EntityFramework代码首先添加不必要的外键
我的POCO里有两门课Entity framework EntityFramework代码首先添加不必要的外键,entity-framework,ef-code-first,Entity Framework,Ef Code First,我的POCO里有两门课 public class Listing { public int ListingId { get; set; } [ForeignKey("Seller")] public int SellerId { get; set; } public virtual User Seller { get; set; } [Required] public string ItemCategory { get; set; }
public class Listing
{
public int ListingId { get; set; }
[ForeignKey("Seller")]
public int SellerId { get; set; }
public virtual User Seller { get; set; }
[Required]
public string ItemCategory { get; set; }
[Required]
public string ItemName { get; set; }
[Required]
public decimal Cost { get; set; }
public DateTime DateOfPublish { get; set; }
[Required]
public bool SaleStatus { get; set; }
[ForeignKey("Buyer")]
public Nullable<int> BuyerId { get; set; }
public virtual User Buyer { get; set; }
}
公共类列表
{
public int ListingId{get;set;}
[外键(“卖方”)]
public int SellerId{get;set;}
公共虚拟用户卖方{get;set;}
[必需]
公共字符串ItemCategory{get;set;}
[必需]
公共字符串ItemName{get;set;}
[必需]
公共十进制成本{get;set;}
public DateTime DateOfPublish{get;set;}
[必需]
公共布尔销售状态{get;set;}
[外国钥匙(“买方”)]
公共可为空的BuyerId{get;set;}
公共虚拟用户买家{get;set;}
}
及
公共类用户
{
public int UserId{get;set;}
[必需]
公共字符串名{get;set;}
[必需]
公共字符串SecondName{get;set;}
[必需]
公共字符串电子邮件{get;set;}
[必需]
公共字符串密码{get;set;}
公共字符串PhoneNumber{get;set;}
公共字符串地址{get;set;}
公共虚拟ICollection列表{get;set;}
当我将其迁移到数据库中时,我会得到BuyerId、SellerId和User\u UserId
User\u UserId列完全没有必要,但我不确定如何处理我的代码才能将其删除。
卖方
和买方
导航属性在列表
类中定义了两个多对一关系。但是用户
类别中有单个集合导航属性列表
ass.由于EF不知道应该映射到这两个关系中的哪一个,因此它只是将其视为第三个关系,没有相应的引用导航属性,默认为FK nameUser\u UserId
您需要将Listings
属性映射到其中一个引用导航属性。一种方法是使用InverseProperty
属性。或者将其替换为两个集合导航属性,并将它们映射到相应的引用导航属性
很快,更换
public virtual ICollection<Listing> Listings { get; set; }
公共虚拟ICollection列表{get;set;}
与
[反向财产(“卖方”)]
公共虚拟ICollection SellerListings{get;set;}
[反向财产(“买方”)]
公共虚拟ICollection买方列表{get;set;}
看起来像是我已经在我的属性上添加了数据注释的副本
public virtual ICollection<Listing> Listings { get; set; }
[InverseProperty("Seller")]
public virtual ICollection<Listing> SellerListings { get; set; }
[InverseProperty("Buyer")]
public virtual ICollection<Listing> BuyerListings { get; set; }