复杂类型在DDD项目的数据库优先模型中

时间:2014-10-17 10:59:49

标签: c# .net entity-framework entity-framework-6 ef-database-first

让我们说我的EF6项目[数据库优先方法]我有一个名为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; }
}

当我从数据库更新模型时,如何将所有与地址相关的字段作为名为Address的聚合字段(SQL Server 2012)?

据我所知,前进的唯一方法是修改T4模板。如果您唯一建议的解决方案是T4模板更改,请您向我展示一些采取类似策略的示例项目或提供您自己的版本。

3 个答案:

答案 0 :(得分:0)

当您在EF中使用数据库第一种方法时,您将对生成器上的结果类负责。因此,您无法在此方法中获得复杂类型的地址。你应该使用其他方法来获得你想要的东西。如果我是你,我将使用代码优先方法并将映射从现有数据库写入代码中的类。

答案 1 :(得分:0)

您可以使用TPH达到您想要的效果,例如:

在您的课程中,您将拥有以下内容:

1-班人

public class Person
{
    public int Id{get; set;}
    public string Name{get; set;}
}

从班级人员继承的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; }
}
例如,

并在名为“实体”的DbContext类中,您只定义以下

public class Entities: DbContext
{
    public DbSet<Person> People{get; set;}
}

那么这将在您的数据库中生成什么?

1-它将生成一个名为people的表,其中包含来自人员和地址类的属性

2-您可以通过这种方式从人或地址访问人员数据

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 

希望这会对你有所帮助

答案 2 :(得分:0)

您可以使用DTOsAutomapper从应用程序类中抽象域模型类。