简体   繁体   中英

EntityFrameWork model relationship configuration

I'm coding in ef 5 code first solution and i have a model as follow:

public class User
{
   public int Id {get;set;}

   public int Role1Id {get; set;}
   public Role Role1 {get; set;}
}

and another model:

public class Role
{
   public int Id { get; set;}

   public string Title {get; set;}
}

also i configure this model in another class as follow:

  public class UserConfig : EntityTypeConfiguration<User>
    {
        public UserConfig()
        {
            ToTable("User", "dbo");
            // Here i want introduce Role1 as navigation property for Role1Id property
        }
    }

here is the question:How can i config User model to introduce Role1 as navigation property for Role1Id property?

You can use annotation:

public class User
{
   public int Id {get;set;}

   public int Role1Id {get; set;}

   [ForeignKey("Role1Id")]
   public Role Role1 {get; set;}
}

EF should configure it automatically as long as the id matches the field generated in the database schema.

You could try to configure it in UserConfig with the following:

HasRequired(user => user.Role1)
   .WithRequiredDependent()
   .Map(mapping => mapping.MapKey("Role1Id");

This configures it to be required. You can use the HasOption method if it's not required as well.

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