繁体   English   中英

带有Fluent API的外键-代码优先

[英]Foreign Key with Fluent API - Code First

我正在尝试使用FluentAPI建立2类的外键,在实现它的方式上有些困惑。

ApplicationUser使用ASP.NET身份模型,并将UserId作为字符串

public class ApplicationUser : IdentityUser
{
     public virtual List<UserProduct> Orders { get; set; }
}

Product有上列复合键ProductIDProductCategoryID

public class Product 
{
    public int ProductID { get; set; }
    public string ProductCategoryID { get; set; }

    public virtual List<UserProduct> Orders { get; set; }

    ...
}

还有另一个类UserProduct ,它将在ApplicationUserProduct表之间具有多对多关系

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});

如何建立UserProductApplicationUserProduct的外键关系?

您可以将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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM