在实体框架6之前,实体框架无法识别嵌套在其他实体或复杂类型中的实体或复杂类型.当Entity Framework生成模型时,嵌套类型就消失了.
让我们看一个简单的例子,其中我们的基本模型有三个实体Student,Course和Enrollment.
让我们添加一个属性Identity,它是Person类型. Person是另一个实体,包含BirthDate和FatherName属性.
在实体框架术语中,因为它没有身份并且是实体的一部分,所以它是一个实体框架复杂类型,自实体框架的第一个版本以来,我们实际上已经支持复杂类型.
Person类型没有嵌套,如图所示以下代码.
public class Student { public int ID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } public Person Identity { get; set; } public virtual ICollectionEnrollments { get; set; }}public class Person { public Person(string fatherName, DateTime birthDate) { FatherName = fatherName; BirthDate = birthDate; } public string FatherName { get; set; } public DateTime BirthDate { get; set; }}
实体框架将知道在以前的版本中使用Person类型时如何保留它.
通过使用Entity Framework Power Tool,我们将了解Entity Framework如何解释模型.右键单击Program.cs文件并选择Entity Framework→View Entity Data Model(只读)
现在您将看到Identity属性在Student类中定义.
如果此Person类不会被任何其他实体使用,那么我们可以将它嵌套在Student类中,但是这个早期版本的Entity Framework不承认嵌套类型.
在旧版本中,您再次生成模型,不仅类型无法识别,而且因为它不存在,属性也不存在,因此实体框架赢了" t根本保留Person类型.
public class Student { public int ID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } public Person Identity { get; set; } public virtual ICollectionEnrollments { get; set; } public class Person { public Person(string fatherName, DateTime birthDate) { FatherName = fatherName; BirthDate = birthDate; } public string FatherName { get; set; } public DateTime BirthDate { get; set; } }}
使用Entity Framework 6,可以识别嵌套实体和复杂类型.在上面的代码中,您可以看到Person嵌套在Student类中.
当您使用Entity Framework Power Tool来展示Entity Framework这次如何解释模型时,真正的身份属性和Person复杂类型.因此实体框架将保留该数据.
现在您可以看到Identity是嵌套的实体类型,在Entity Framework 6之前不支持.
我们建议您逐步执行上述示例以便更好地理解