简体   繁体   English

实体框架代码优先导航问题

[英]Entity Framework Code First navigation issue

I am trying to setup a navigation property that will hold zero or more elements of another table. 我正在尝试设置一个导航属性,该属性将容纳另一个表的零个或多个元素。 The problem Entity Framework seems to be having is the other table has a composite primary key. 实体框架似乎存在的问题是另一个表具有复合主键。

public class Alpha
{
    public int Id { get; set; }
    public int? BetaId { get; set; }
    public virtual ICollection<Beta> Beta { get; set; }
    public string Name { get; set; }
}

public class Beta
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int SequenceNumber { get; set; }
    public string Name { get; set; }
}

public class ABContext : DbContext
{
    public DbSet<Alpha> Alpha { get; set; }
    public DbSet<Beta> Beta { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Beta>()
            .HasKey(b => new { b.Id, b.SequenceNumber });
    }
}

I am not sure how to properly setup the relationship. 我不确定如何正确建立关系。 I've tried several different things. 我尝试了几种不同的方法。 Entity Framework either complains about not using both keys from the Beta class to define the navigation property, or creates a pair of extra columns in the Alphas table that doesn't properly link the tables. 实体框架要么抱怨没有使用Beta类中的两个键来定义导航属性,要么抱怨在Alphas表中创建一对额外的列,这些列无法正确链接表。

The goal is Alpha should hold a set of zero or more Betas based on Beta.Id . 目标是Alpha应该基于Beta.Id持有一组零个或多个Beta.Id A Beta may belong to zero or more Alphas. Beta可能属于零个或多个Alpha。 However, I'm not really interested in the Beta to Alpha relationship. 但是,我对Beta与Alpha关系并不真正感兴趣。

Any ideas? 有任何想法吗?

So let's have a look at your requirements: 因此,让我们看一下您的要求:

Alpha should hold set of zero or more Betas .... A Beta may belong to zero or more Alphas Alpha应该拥有零个或多个Beta的集合...。Beta可能属于零个或多个Alpha

It is many-to-many relation so you have to map it. 这是多对多关系,因此您必须进行映射。

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Beta>()
        .HasKey(b => new { b.Id, b.SequenceNumber });

    modelBuilder.Entity<Alpha>()
        .HasMany(a => a.Beta)
        .WithMany();
}

This will create additional table in database with trhee columns (probably called Alpha_Id, Beta_Id and Beta_SequenceNumber). 这将在数​​据库中创建带有trhee列(可能称为Alpha_Id,Beta_Id和Beta_SequenceNumber)的其他表。

I still don't underestand what do you mean by based on Beta.Id . 我仍然不理解, 基于Beta.Id意味着什么。 If alpha can hold only records with the same Beta.Id you will probably have to control this in the application logic. 如果alpha只能保存具有相同Beta.Id的记录,则可能必须在应用程序逻辑中对此进行控制。 It is something that would need additional complicated constructs to be enforced by mapping. 这需要通过映射来实施其他复杂的构造。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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