0
  • 火鸟 2.5
  • 实体框架 5
  • 火鸟客户端DLL 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; }
}

公共类 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...

4

1 回答 1

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);
    }
于 2012-11-20T13:55:57.260 回答