c# - 组合键作为外键

标签 c# entity-framework ef-code-first foreign-keys composite-key

我在 MVC 3 应用程序中使用 Entity Framework 4.1。我有一个实体,其中我的主键由两列(复合键)组成。这在另一个实体中用作外键。如何建立关系?在正常情况下,我们使用:

public class Category
{
    public string CategoryId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Product> Products { get; set; }
}

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public string CategoryId { get; set; }

    public virtual Category Category { get; set; }
} 

但是如果类别有两列键怎么办?

最佳答案

您可以使用任一流畅的 API:

public class Category
{
    public int CategoryId1 { get; set; }
    public int CategoryId2 { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Product> Products { get; set; }
}

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public int CategoryId1 { get; set; }
    public int CategoryId2 { get; set; }

    public virtual Category Category { get; set; }
}

public class Context : DbContext
{
    public DbSet<Category> Categories { get; set; }
    public DbSet<Product> Products { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Category>()
            .HasKey(c => new {c.CategoryId1, c.CategoryId2});

        modelBuilder.Entity<Product>()
            .HasRequired(p => p.Category)
            .WithMany(c => c.Products)
            .HasForeignKey(p => new {p.CategoryId1, p.CategoryId2});

    }
}

或者数据注释:

public class Category
{
    [Key, Column(Order = 0)]
    public int CategoryId2 { get; set; }
    [Key, Column(Order = 1)]
    public int CategoryId3 { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Product> Products { get; set; }
}

public class Product
{
    [Key]
    public int ProductId { get; set; }
    public string Name { get; set; }
    [ForeignKey("Category"), Column(Order = 0)]
    public int CategoryId2 { get; set; }
    [ForeignKey("Category"), Column(Order = 1)]
    public int CategoryId3 { get; set; }

    public virtual Category Category { get; set; }
}

关于c# - 组合键作为外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5436731/

相关文章:

entity-framework - 为什么 Entity Framework 缺少以 'Status' 结尾的表中的最后一个 s

c# - Entity Framework 将占位符值映射为 null

c# - 使用 Fluent API 为没有导航属性的实体定​​义外键

c# - 包含循环,如果引用跟踪被禁用,则无法序列化,json.net 和 webapi

javascript - ASP.NET 中的 SignalR 和 Angular,客户端没有得到响应

c# - .NET 隔离存储文件锁定引发 NRE

c# - 如何使用azure通信服务从web api发送电子邮件

c# - 我应该为 EF6 实现存储库和工作单元吗?

ef-code-first - EF Code First - 无效的列名

C# 我的数据对象集合应该在哪里实例化?