Mvc,外键关系

时间:2014-09-26 07:44:01

标签: c# asp.net-mvc ef-fluent-api

我使用Mvc(Country - > State - > City)并希望使用Fluent Api进行外键关系,然后这里是模型。

public class Country
{
    public int Country_Id { get; set; }
    public String Country_Name { get; set; }
}
public class State
{
    public string State_Name { get; set; }
    public int State_Id { get; set; }
    public virtual Country Country { get; set; }
}
public class City
{
    public string City_Name { get; set; }
    public int City_Id { get; set; }
    public virtual State State { get; set; }
}

现在我创建UserContext类来定义DbContext和Fluent api 任何人都可以知道如何在这些实体之间建立关系

public class UsersContext : DbContext
{
    public UsersContext()
        : base("DefaultConnection") {}

    public DbSet<UserProfile> UserProfiles { get; set; }
    public DbSet<Country> TbCountries { get; set; }
    public DbSet<State> TbState { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        //Country
        modelBuilder.Entity<Country>().HasKey(c => c.Country_Id);
        modelBuilder.Entity<Country>().Property(p => p.Country_Name).HasColumnType("VARCHAR").IsRequired().HasMaxLength(50);
        //State
    } 

1 个答案:

答案 0 :(得分:0)

您可以为每个实体类创建一个配置类:

internal partial class CountryConfiguration : EntityTypeConfiguration<Country>
    {
        public CountryConfiguration()
        {
            ToTable("dbo.Country");
            HasKey(x => x.Country_Id);

            Property(x => x.Country_Id).HasColumnName("Country_Id").IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            Property(x => x.Country_Name).HasColumnName("Country_Name").IsOptional().HasMaxLength(255);
        }
}


internal partial class StateConfiguration : EntityTypeConfiguration<State>
{
        public StateConfiguration()
        {
            ToTable("dbo.State");
            HasKey(x => x.State_Id);

            Property(x => x.State_Id).HasColumnName("State_Id").IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            Property(x => x.State_Name).HasColumnName("State_Name").IsOptional().HasMaxLength(255);
            // Foreign keys
            HasOptional(a => a.Country).WithMany(b => b.States).HasForeignKey(c => c.CountryId); 
        }
}

然后在你的OnModelCreating方法中,你可以像这样连接它们:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new CountryConfiguration());
        modelBuilder.Configurations.Add(new StateConfiguration());
    } 

如果您已经有一个现有的数据库,那么有very handy tool可以从数据库中生成代码优先的POCO类。