DDD项目的数据库第一模型中的复杂类型

本文关键字:复杂 模型 类型 项目 数据库 DDD | 更新日期: 2023-09-27 18:26:56

假设在我的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; }
}

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

据我所知,唯一的出路就是修改T4模板。如果你唯一建议的解决方案是T4模板替换,你能给我看一些采用类似策略的示例项目吗?或者提供你自己的版本。

DDD项目的数据库第一模型中的复杂类型

当您在EF中使用数据库优先的方法时,您将对生成的类承担所有责任。因此,在这种方法中无法获得复杂类型的Address。你应该用其他方法得到你想要的。如果我是你,我会使用代码优先的方法,并在代码中编写从现有数据库到类的映射。

您可以使用TPH来实现您想要的目标,例如:

在你的课堂上,你会有以下内容:

一类人

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的表,该表包含来自person和地址类的属性

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 

希望这将帮助您

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