实体框架代码优先 - 加入复合密钥

时间:2012-11-20 09:35:00

标签: entity-framework ef-code-first firebird entity-framework-5

  • Firebird 2.5
  • 实体框架5
  • FirebirdClientDll 3.0.0.0

我(仍然)尝试使用实体框架(代码优先)访问我的旧数据库。

现在我想在没有Forrein Key的情况下创建一对一关系。

public class KONTAKTE
{
    public int KUNDENNR { get; set; }
    public Int16 ANSPRNR { get; set; }
    public Int16 NR { get; set; }

    public virtual ICollection<KONTAKTBED> KONTAKTBED { get; set; }
}
public class KONTAKTBED
{
    public int ID { get; set; }

    public Int16 LFDNR { get; set; }
    public int KUNDENNR { get; set; }
    public Int16 ANSPRNR { get; set; }

    public string NAME { get; set; }
}

public class CTKontakt:DbContext     {

    public DbSet<KONTAKTE> KONTAKTE { get; set; }
    public DbSet<KONTAKTBED> KONTAKTBED { get; set; }

    public CTKontakt(DbConnection connectionString) : base(connectionString, false)
    {
        Database.SetInitializer<CTKontakt>(null);
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

       /* modelBuilder.Entity<KONTAKTE>().
        HasMany(p => p.KONTAKTBED).
        WithMany().
        Map(t => t.MapLeftKey("KUNDENNR", "NR")
            .MapRightKey("KUNDENNR", "LFDNR"));*/ //Does't work

        modelBuilder.Entity<KONTAKTE>().HasKey(a => new { a.KUNDENNR, a.ANSPRNR, a.NR });     
        modelBuilder.Entity<KONTAKTBED>().HasKey(a => new { a.ID, a.DATABASE_ID});  

        base.OnModelCreating(modelBuilder);
    }

如您所见,我无法使用KONTAKTE-Table的整个主键。这是否意味着我必须实现多对多的实现?目前我只是稍后加入表格:

from k in lEKontakt.KONTAKTE
join kbed in lEKontakt.KONTAKTBED
on new { KUNDENNR = k.KUNDENNR, NR = k.NR }
equals new { KUNDENNR = kbed.KUNDENNR, NR = kbed.LFDNR }

我想做这样的事情:

modelBuilder.Entity<KONTAKTE>()
.HasKey(d => new { d.KUNDENNR, d.ANSPRNR, d.NR })
.HasMany(d => d.KONTAKTBED)
.WithOptional()
.HasForeignKey(l => new { l.KUNDENNR, l.ANSPRNR, l.LFDNR });

但没有ANSPRNR ......

我还是Ef-Code First的新手,我发现的所有样品似乎都不适用于EF 5 ......

1 个答案:

答案 0 :(得分:1)

我为我找到了一个解决方案:

似乎我只需要删除未使用字段的主键定义。我仍然可以在没有它的情况下阅读数据:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        modelBuilder.Entity<KONTAKTE>()
            .HasRequired(b => b.KUNDEN)
            .WithMany()
            .HasForeignKey(b => b.KUNDENNR);

        modelBuilder.Entity<KONTAKTE>()
        .HasKey(d => new { d.KUNDENNR, d.NR })
        .HasMany(d => d.KONTAKTBED)
        .WithOptional()
        .HasForeignKey(l => new { l.KUNDENNR, l.LFDNR });

        modelBuilder.Entity<KONTAKTE>().HasKey(a => new { a.KUNDENNR, a.NR });     

        modelBuilder.Entity<KUNDEN>().HasKey(a => new { a.KUNDENNR });

        modelBuilder.Entity<KONTAKTBED>().HasKey(a => new { a.ID, a.DATABASE_ID});  

        base.OnModelCreating(modelBuilder);
    }