[英]Foreign Key with Fluent API - Code First
I am trying to establish foreign key to 2 classes using FluentAPI and bit confused on the way to implement it. 我正在尝试使用FluentAPI建立2类的外键,在实现它的方式上有些困惑。
ApplicationUser
uses ASP.NET Identity model and has UserId as string ApplicationUser
使用ASP.NET身份模型,并将UserId作为字符串
public class ApplicationUser : IdentityUser
{
public virtual List<UserProduct> Orders { get; set; }
}
Product
that has a composite key on columns ProductID
and ProductCategoryID
Product
有上列复合键ProductID
和ProductCategoryID
public class Product
{
public int ProductID { get; set; }
public string ProductCategoryID { get; set; }
public virtual List<UserProduct> Orders { get; set; }
...
}
and another class UserProduct
that will have many-to-many relationship between ApplicationUser
and Product
table 还有另一个类
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; }
}
The FluentAPI code looks like 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});
How do I establish the foreign key relationship of UserProduct
with ApplicationUser
and Product
? 如何建立
UserProduct
与ApplicationUser
和Product
的外键关系?
You can add the id-property (eg OrderId) to the class UserProduct and use this code to connect entities by foreign key. 您可以将id属性(例如OrderId)添加到UserProduct类,并使用此代码通过外键连接实体。
modelBuilder.Entity<UserProduct>()
.HasRequired(x => x.User)
.WithMany(u => u.Orders)
.HasForeignKey(x => x.OrderId);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.