简体   繁体   中英

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.

The goal is Alpha should hold a set of zero or more Betas based on Beta.Id . A Beta may belong to zero or more Alphas. However, I'm not really interested in the Beta to Alpha relationship.

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

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).

I still don't underestand what do you mean by based on Beta.Id . If alpha can hold only records with the same Beta.Id you will probably have to control this in the application logic. It is something that would need additional complicated constructs to be enforced by mapping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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