简体   繁体   中英

How to set foreign key where column names are different using Entity Framework 5 Fluent API?

I am trying to establish a foreign key relationship between following domain classes using Fluent API (Entity Framework v5):

public partial class User
{
    public long UserID { get; set; }
    public string UserName { get; set; }
}
public partial class AccountGroup : BaseEntity
{
    public long AccountGroupID { get; set; }
    public string Name { get; set; }
    public long ModifiedBy { get; set; }
    public virtual User User { get; set; }
}

Fluent API

builder.Entity<User>().HasKey(p => p.UserID); //Set User Id as primary key
builder.Entity<AccountGroup>().HasKey(x => x.AccountGroupID); //SetAccountGroupId as PK

I am not sure how to set a relationship between User.UserId and AccountGroup.ModifiedBy column using fluent API. I can do this by Data Annotation but I am looking for a solution using fluent api

Remove the ModifiedBy property from your entity:

public partial class AccountGroup
{
    public long AccountGroupID { get; set; }
    public string Name { get; set; }
    public virtual User User { get; set; }
}

And then map the foreign key like so:

builder.Entity<AccountGroup>()
    .HasRequired(x => x.User)
    .WithMany()
    .Map(m => m.MapKey("ModifiedBy"));

Use HasOptional instead if the foreign key should be nullable:

builder.Entity<AccountGroup>()
    .HasOptional(x => x.User)
    .WithMany()
    .Map(m => m.MapKey("ModifiedBy"));

You also don't need to specify the primary keys like you are. Entity Framework will discover those by convention.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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