【问题标题】:Foreign Key with Fluent API - Code First使用 Fluent API 的外键 - 代码优先
【发布时间】: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 在列 ProductIDProductCategoryID 上有一个复合键

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

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

    ...
}

另一个类 UserProductApplicationUserProduct 表之间具有多对多关系

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的外键关系?

【问题讨论】:

标签: c# ef-code-first ef-fluent-api


【解决方案1】:

您可以将 id 属性(例如 OrderId)添加到类 UserProduct 中,并使用此代码通过外键连接实体。

modelBuilder.Entity<UserProduct>()
            .HasRequired(x => x.User) 
            .WithMany(u => u.Orders) 
            .HasForeignKey(x => x.OrderId);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    • 2012-04-09
    • 2012-05-29
    • 2014-03-15
    • 2013-09-04
    相关资源
    最近更新 更多