我正在使用Mvc(国家->省->城市),并希望使用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
}
最佳答案
您可以为每个实体类创建一个配置类:
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类。
关于c# - Mvc,外键关系,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26054520/