简体   繁体   English

使用流利的api在实体框架中进行一对多映射

[英]One to many mapping in Entity framework with fluent api

I find many examples about this but no one works for me... 我找到了许多与此相关的示例,但没有人适合我...

I have principal class: 我有校长班:

public class Class1
{
    public int id { get; set; }
    public string desc { get; set; } 
    public virtual Class2 class2 {get; set;}
}

and the second class: 第二类:

public class Class2
{
    public int id { get; set; }
    public string desc { get; set; } 
}

I am mapping Class1 in this way 我以这种方式映射Class1

public class Class1Map : EntityTypeConfiguration<Class1>
{
    public Class1Map()
    {
        // Primary Key
        this.HasKey(t => t.Id);

        // Table & Column Mappings
        this.ToTable("Class1TableName");
        this.Property(t => t.id).HasColumnName("IdColumnName");
        this.Property(t => t.desc).HasColumnName("DescColumName");
    }
}

and this works well 这很好

but I try many ways to bind Class2 property of Class1 to IdClass2ColumnName field of Class1Tablename as foreign key linked to IdColumnName of Class2 table without success. 但是我尝试了多种方法将Class1 Class2属性绑定到IdClass2ColumnName字段,作为链接到Class2表的Class1Tablename外键, IdColumnName成功。

As you can see I don't want to put also IdClass2 property in Class1 如您所见,我不想将IdClass2属性也IdClass2 Class1

For testing I tried without success: 为了测试,我尝试没有成功:

this.HasRequired(t => t.class2)
    .WithRequiredPrincipal()
    .Map(m => m.MapKey("IdClass2ColumnName "));


this.HasRequired(t => t.class2)
    .WithMany()
    .Map(m => m.MapKey("IdClass2ColumnName"));

Solved, was a problem in code migration, I forget to update code migration class and so EF use old column name. 解决了,这是代码迁移中的一个问题,我忘记了更新代码迁移类,因此EF使用了旧的列名。

The correct mapping syntax is 正确的映射语法是

this.HasRequired(t => t.class2)
    .WithRequiredDependent()
    .Map(m => m.MapKey("IdClass2ColumnName "));

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

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