开发者

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(Da开发者_运维问答tabaseGeneratedOption.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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜