C# foreach在创建之前访问的阴影属性
我是实体框架的新手,我正在学习Julie Lerman的Pluralsight课程。我正在看第二个课程,但我使用的是EF Core 2.1 编辑: 因此,我决定对所有内容进行注释,然后再次按照课程进行操作,现在可以正常工作了,但生成的迁移将生成两列,这两列不应该出现:C# foreach在创建之前访问的阴影属性,c#,entity-framework,entity-framework-core,ef-core-2.1,C#,Entity Framework,Entity Framework Core,Ef Core 2.1,我是实体框架的新手,我正在学习Julie Lerman的Pluralsight课程。我正在看第二个课程,但我使用的是EF Core 2.1 编辑: 因此,我决定对所有内容进行注释,然后再次按照课程进行操作,现在可以正常工作了,但生成的迁移将生成两列,这两列不应该出现: protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<DateTime>(
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);
}
武士
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>();
}
}
公共级武士
{
公共int Id{get;set;}
公共字符串名称{get;set;}
PublicPersonFullName BetterName{get;set;}
公共列表引号{get;set;}
公共列表武士战机{get;set;}
公共秘密秘密{get;set;}
公共武士()
{
Quotes=新列表();
SamuraiBattles=新列表();
}
}
致以最良好的祝愿,
Adriano。这是因为
foreach
循环也定义了所属实体的阴影属性。请记住,根据EF核心术语,拥有的实体仍然是实体,因此GetEntityTypes()
将它们包括在结果集中
EF Core提供扩展方法,可用于识别它们并进行特殊处理,或者在这种特殊情况下,只需跳过它们:
foreach (var entityType in modelBuilder.Model.GetEntityTypes().Where(t => !t.IsOwned())
{
// ...
}
同样,这样的循环应该在发现所有实体和拥有的实体类型之后进行。如果
PersonFullName
没有标记[Owned
]属性,请在OwnsOne
调用后移动foreach
(或者最好在OnModelCreating
的末尾)。非常感谢,两种方法都试过了,都成功了。
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>();
}
}
foreach (var entityType in modelBuilder.Model.GetEntityTypes().Where(t => !t.IsOwned())
{
// ...
}