How to match parent column in EF 4.1 code first

In my project, I have the following DomainModel.

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

I use the free configuration as shown 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 the repository to get all the Logins data looks like this:

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

When I execute the code, I get the following error:

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

Can anyone suggest what I'm doing wrong here?

Thanks in advance

+4
source share
1 answer

..

.HasForeignKey(x => x.CreatedBy) .

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

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

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

All Articles