【发布时间】:2015-08-19 08:23:56
【问题描述】:
我正在尝试使用 FluentAPI 为 2 个类建立外键,在实现它的过程中有点困惑。
ApplicationUser 使用 ASP.NET Identity 模型,并将 UserId 作为字符串
public class ApplicationUser : IdentityUser
{
public virtual List<UserProduct> Orders { get; set; }
}
Product 在列 ProductID 和 ProductCategoryID 上有一个复合键
public class Product
{
public int ProductID { get; set; }
public string ProductCategoryID { get; set; }
public virtual List<UserProduct> Orders { get; set; }
...
}
另一个类 UserProduct 在 ApplicationUser 和 Product 表之间具有多对多关系
public partial class UserProduct
{
public string UserId { get; set; }
public int ProductID { get; set; }
public string ProductCategoryID { get; set; }
public virtual ApplicationUser User { get; set; }
public virtual Product Product { get; set; }
}
FluentAPI 代码如下所示
modelBuilder.Entity<Product>().Property(t => t.ProductID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<Product>().HasKey(x => new { x.ProductID, x.ProductCategoryID });
modelBuilder.Entity<UserProduct>().HasKey(x => new {x.UserId, x.ProductID, x.ProductCategoryID});
如何建立UserProduct与ApplicationUser和Product的外键关系?
【问题讨论】:
标签: c# ef-code-first ef-fluent-api