我是实体框架新手,正在通过 Julie Lerman 的 Pluralsight 课程学习 ATM。我正在看第二课”实体框架核心 2:映射 https://app.pluralsight.com/library/courses/e-f-core-2-beyond-the-basics-mappings“但我使用的是 EF Core 2.1。
编辑:
所以我决定注释掉所有内容并再次按照课程进行操作,它现在正在工作,但是生成的迁移生成了不应该存在的两列:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<DateTime>(
name: "BetterName_Created",
table: "Samurais",
nullable: false,
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));
migrationBuilder.AddColumn<string>(
name: "GivenName",
table: "Samurais",
nullable: true);
migrationBuilder.AddColumn<DateTime>(
name: "BetterName_LastModified",
table: "Samurais",
nullable: false,
defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified));
migrationBuilder.AddColumn<string>(
name: "SurName",
table: "Samurais",
nullable: true);
}
SamuraiContext.cs
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<SamuraiBattle>().HasKey(s => new { s.SamuraiId, s.BattleId });
modelBuilder.Entity<Battle>().Property(b => b.StartDate).HasColumnType("Date");
modelBuilder.Entity<Battle>().Property(b => b.EndDate).HasColumnType("Date");
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
modelBuilder.Entity(entityType.Name).Property<DateTime>("Created");
modelBuilder.Entity(entityType.Name).Property<DateTime>("LastModified");
}
modelBuilder.Entity<Samurai>().OwnsOne(s => s.BetterName).Property(b => b.GivenName).HasColumnName("GivenName");
modelBuilder.Entity<Samurai>().OwnsOne(s => s.BetterName).Property(b => b.SurName).HasColumnName("SurName");
}
在添加 GiveName/Surname 之前,foreach 上下文已经构建完毕,直到一切按预期工作。但是在添加列名的最后 2 行后,它添加了 BetterName_Created 和 BetterName_LastModified 为什么? (根据课程不应该)
PersonFullName.cs
public class PersonFullName
{
public string SurName { get; set; }
public string GivenName { get; set; }
public string FullName => $"{GivenName} {SurName}";
public string FullNameReverse => $"{SurName}, {GivenName}";
public PersonFullName(string givenName, string surName)
{
SurName = surName;
GivenName = givenName;
}
}
Samurai.cs
public class Samurai
{
public int Id { get; set; }
public string Name { get; set; }
public PersonFullName BetterName { get; set; }
public List<Quote> Quotes { get; set; }
public List<SamuraiBattle> SamuraiBattles { get; set; }
public SecretIdentity SecretIdentity { get; set; }
public Samurai()
{
Quotes = new List<Quote>();
SamuraiBattles = new List<SamuraiBattle>();
}
}
此致,
阿德里亚诺.