如何在 entity framework 中将多个实体合并为一个(将复杂实体映射为单个实体 table)
How to combine several entities into one in entity framework (map complex entity into single table)
举个例子。我有两个型号
public class Person {
public int Id { get; set: }
public string Name { get; set; }
public Birth Date { get; set; }
}
public class Birth {
public int Year { get; set; }
public int Month { get; set; }
public int Day { get; set; }
}
如何让 entity framework 像这样看到 'Person' 实体:
public class Person {
public int Id { get; set: }
public string Name { get; set; }
public int Year { get; set; }
public int Month { get; set; }
public int Day { get; set; }
}
即EF 应该将其映射到单个 table.
如果您使用的是 EF Core,这可以通过所谓的 "Owned Entities" 实现。使用属性:
public class Person
{
public int Id { get; set: }
public string Name { get; set; }
public Birth Date { get; set; }
}
[Owned]
public class Birth
{
public int Year { get; set; }
public int Month { get; set; }
public int Day { get; set; }
}
或显式配置:
modelBuilder.Entity<Person>().OwnsOne(p => p.Date);
请注意,Birth
个字段将带有前缀。
举个例子。我有两个型号
public class Person {
public int Id { get; set: }
public string Name { get; set; }
public Birth Date { get; set; }
}
public class Birth {
public int Year { get; set; }
public int Month { get; set; }
public int Day { get; set; }
}
如何让 entity framework 像这样看到 'Person' 实体:
public class Person {
public int Id { get; set: }
public string Name { get; set; }
public int Year { get; set; }
public int Month { get; set; }
public int Day { get; set; }
}
即EF 应该将其映射到单个 table.
如果您使用的是 EF Core,这可以通过所谓的 "Owned Entities" 实现。使用属性:
public class Person
{
public int Id { get; set: }
public string Name { get; set; }
public Birth Date { get; set; }
}
[Owned]
public class Birth
{
public int Year { get; set; }
public int Month { get; set; }
public int Day { get; set; }
}
或显式配置:
modelBuilder.Entity<Person>().OwnsOne(p => p.Date);
请注意,Birth
个字段将带有前缀。