给出两个对象:
public class Region
{
public Guid Id { get; set; }
[Key]
public int RegionId { get; set; }
public string Name { get; set; }
public virtual ICollection<District> Districts { get; set; }
}
和
public class District
{
public Guid Id { get; set; }
[Key]
public int DistrictId { get; set; }
public string Name { get; set; }
public virtual ICollection<Building> Buildings { get; set; }
public int RegionId { get; set; }
public Region Region { get; set; }
}
在dbContext中如下:
modelBuilder.Entity<Region>()
.HasMany(d => d.Districts);
modelBuilder.Entity<Region>()
.HasIndex(b => b.RegionId)
.IsUnique()
.HasName("Index_RegionId");
modelBuilder.Entity<District>()
.HasIndex(d => d.DistrictId)
.IsUnique()
.HasName("Index_DistrictId");
modelBuilder.Entity<District>()
.HasOne(p => p.Region)
.WithMany(d => d.Districts)
.HasForeignKey(r => r.RegionId);
运行迁移并创建数据库后,我想从SQL中填充数据库,例如:
INSERT INTO [dbo].[Regions](RegionId, Name)
VALUES
(
1, 'Some Region'
);
在CREATE TABLE语句中可以执行以下操作:ID UNIQUEIDENTIFIER DEFAULT NEWID()
。如何在CodeFirst中为无PK字段自动生成Guid?我应该在DBContext类中写什么,或者如何解决?