比方说,在我的EF6项目数据库优先方法中,我有一个名为Address的复杂类型,只是为了澄清我的复杂类型没有任何标识,它只是独立数据聚合的合并,它甚至不负责自己的持久性
目前,我将与address关联的所有字段作为address组成部分的直接属性,并为Person类自动生成以下定义:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public Nullable<int> Easting { get; set; }
public Nullable<int> Northing { get; set; }
public string Building { get; set; }
public string County { get; set; }
public string PostCode { get; set; }
public string StreetName { get; set; }
public string StreetNumber { get; set; }
public string Town { get; set; }
public string Unit { get; set; }
public string Village { get; set; }
public int CountryId { get; set; }
}理想情况下,我希望每次从数据库中更新模型时都会有如下内容
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public Address Address { get; set; }
}
public class Address
{
public Nullable<int> Easting { get; set; }
public Nullable<int> Northing { get; set; }
public string Building { get; set; }
public string County { get; set; }
public string PostCode { get; set; }
public string StreetName { get; set; }
public string StreetNumber { get; set; }
public string Town { get; set; }
public string Unit { get; set; }
public string Village { get; set; }
public int CountryId { get; set; }
}从数据库(SQL Server 2012)更新模型时,如何将所有与地址相关的字段作为名为address的聚合字段?
据我所知,唯一的办法就是修改T4模板。如果你唯一建议的解决方案是T4模板交替,你可以给我一些样本项目采取类似的策略或提供你自己的版本。
发布于 2014-10-26 15:33:12
当您在EF中使用数据库优先方法时,您将生成的类的所有责任都放在生成器上。所以在这种方法中你不能得到复杂类型的地址。你应该使用其他方法来获得你想要的东西。如果我是你,我会使用代码优先的方法,用代码编写从现有数据库到类的映射。
发布于 2014-10-26 15:50:50
您可以使用TPH来实现您想要的功能,例如:
在您的课程中,您将拥有以下内容:
1级人员
public class Person
{
public int Id{get; set;}
public string Name{get; set;}
}从person类继承的2类地址
public class Address: Person
{
public int? Easting { get; set; }
public int? Northing { get; set; }
public string Building { get; set; }
public string County { get; set; }
public string PostCode { get; set; }
public string StreetName { get; set; }
public string StreetNumber { get; set; }
public string Town { get; set; }
public string Unit { get; set; }
public string Village { get; set; }
public int CountryId { get; set; }
}例如,在名为"Entities“的DbContext类中,您仅定义了以下内容
public class Entities: DbContext
{
public DbSet<Person> People{get; set;}
}那么这将在您的数据库中生成什么呢?
1-它将生成一个名为people的表,其中包含person和address类的属性
2-您可以通过这种方式从person或from address访问人员数据
var db=new Entities();
var person= db.People.OfType<Person>(); // this will give you only Id and Name properties
var address= db.People.OfType<Address>(); // this will give you the person and address details together 希望这能对你有所帮助
发布于 2014-10-26 22:22:53
您可以使用DTOs和Automapper从应用程序类中抽象域模型类。
https://stackoverflow.com/questions/26423564
复制相似问题