How to map parent column in EF 4.1 code first
Asked Answered
F

1

4

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

Freewheel answered 16/7, 2011 at 11:24 Comment(0)
R
5

.. 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"));
Robinett answered 16/7, 2011 at 11:42 Comment(3)
Thanks for you reply. Actually I don't want to change my domain model. Because I think my DomainModel is correct. I don't like to change my domain model for ORM. Just wondering how can I tell my ORM to load CreatedBy as Login object?Freewheel
@Freewheel edited answer. use Map(x => x.MapKey("ForeignKeyColumn")) to configure the FK columnRobinett
Getting same 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.Freewheel

© 2022 - 2024 — McMap. All rights reserved.