这里有我的域实体:
public class Province
{
private ICollection<City> _cities;
public virtual ICollection<City> Cities
{
get { return _cities ?? (_cities = new HashSet<City>()); }
set { _cities = value; }
}
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual double Latitude { get; set; }
public virtual double Longitude { get; set; }
}
public class City
{
private Province _province;
public virtual Province Province
{
get { return _province ?? (_province = new Province()); }
set { _province = value; }
}
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Latitude { get; set; }
public virtual string Longitude { get; set; }
}
映射:
public class ProvinceMap : EntityTypeConfiguration<Province>
{
public ProvinceMap()
{
this.ToTable("Province");
this.HasKey(p => p.Id);
this.Property(x => x.Id).HasColumnName("Id");
this.Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(x => x.Name).HasMaxLength(50).IsRequired();
this.Property(x => x.Latitude).IsRequired();
this.Property(x => x.Longitude).IsRequired();
//this.HasMany(x => x.Cities)
// .WithRequired(x => x.Province)
// .HasForeignKey(x => x.Id);
}
}
public class CityMap : EntityTypeConfiguration<City>
{
public CityMap()
{
this.ToTable("City");
this.HasKey(x => x.Id);
this.Property(x => x.Id).HasColumnName("Id");
this.Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.Property(x => x.Name).HasMaxLength(50).IsRequired();
this.Property(x => x.Latitude).IsRequired();
this.Property(x => x.Longitude).IsRequired();
this.HasRequired(x => x.Province)
.WithMany(x => x.Cities)
.HasForeignKey(x => x.Id);
}
}
上下文:
public class DataContext : DbContext
{
public DataContext(): base("DataContext")
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DataContext, Configuration>("DataContext"));
}
public DbSet<Province> Provinces { get; set; }
public DbSet<City> Cities { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ProvinceMap());
modelBuilder.Configurations.Add(new CityMap());
//base.OnModelCreating(modelBuilder);
}
}
当我在 Nuget 包控制台运行“update-database”命令时,出现错误:
连接“City_Province”中的元素角色“City_Province_Source”中的多重性无效。因为 Dependent Role 指的是关键属性,所以多重属性 Dependent Role 的上限必须等于“1”。