How to map parent column in EF 4.1 code first

若如初见. 提交于 2019-12-23 12:37:16

问题


In my project I have following DomainModel.

public class Login
{
    public Guid Id { get; set; }
    public Login CreatedBy {get; set; }
}

I am using fluent configuration as below:

modelBuilder.Entity<Login>()
            .HasKey(x => x.Id)
            .ToTable("Login");

modelBuilder.Entity<Login>()
            .HasOptional(x => x.CreatedBy)
            .WithMany()
            .HasForeignKey(x => x.CreatedBy);

My code in repository to get all Logins data is as below:

return from d in Db.Logins.Include("CreatedBy") 
       select d;

When I execute the code I am getting following error:

The foreign key component 'CreatedBy' is not a declared property on type 'Login'. Verify that it has not been explicitly excluded from the model and that it is a valid primitive property.

Can anyone suggest what I am doing wrong here?

Thanks in advance


回答1:


.. has not been explicitly excluded from the model and that it is a valid primitive property

Your foreign key mapping .HasForeignKey(x => x.CreatedBy) does not use a primitive property.

public class Login
{
    public Guid Id { get; set; }
    public virtual Login CreatedBy {get; set; }
}

Then map it like

modelBuilder.Entity<Login>()
            .HasKey(x => x.Id)
            .ToTable("Login");

modelBuilder.Entity<Login>()
            .HasOptional(x => x.CreatedBy)
            .WithMany()
            .Map(x => x.MapKey("ForeignKeyColumn"));


来源:https://stackoverflow.com/questions/6717007/how-to-map-parent-column-in-ef-4-1-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!