如何查看ADO.NET实体数据模型的代码
我创建了ADO.NET实体数据模型。我可以去哪里查看实际的课程?我想检查数据类型并添加一些DisplayName
属性。如何查看ADO.NET实体数据模型的代码
这里是从Solution Explorer模型:
感谢。
当您从数据库生成模型(这里看起来就是这种情况)时,会创建几个不同的代码文件。要获取上下文的代码,请展开ProgramMasterList.Context.tt
。你会看到一个.cs文件,用于上下文类。
然后,对于您从数据库中选择的每个表作为模型的一部分,将创建一个实体类。你可以通过扩展ProgramMasterList.tt
找到这些。例如,如果您有一个名为Person的表,则可能有一个实体类文件Person.cs
,其中定义了Person
类。
现在,你提到想要修改类来添加属性。如果您修改由实体框架动态生成的ProgramMasterList.tt
下的类文件,那么下次您从数据库更新模型(例如将数据库中的新表添加到模型中)时,您所做的任何更改将被覆盖。幸运的是,还有更好的方法。 ProgramMasterList.tt
下的每个班级是部分班。因此,您可以添加到该类而不修改实体框架自动生成的文件。只需创建一个新文件,声明Person类(作为部分),并在其中添加额外的方法,属性等。我建议将所有这些“扩展名”放在一个文件夹中,以保持它们的组织性,但这取决于您。
因此,它可能是这个样子:
解决方案结构:
- ProgramMasterList.edmx
- ProgramMasterList.Context.tt
- ProgramMasterList.Context.cs
个
- ProgramMasterList.Designer.cs
- ProgramMasterList.edmx.diagram
- ProgramMasterList.tt
- Person.cs
- ProgramMasterList.Context.tt
- 扩展
- Person.cs
Person.cs(下ProgramMasterList.tt)
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace SomeNamespace
{
using System;
using System.Collections.Generic;
public partial class Person
{
public Person()
{
}
public int PersonID { get; set; }
public string Name { get; set; }
public DateTime Birthdate { get; set; }
}
}
人。cs(在扩展文件夹中) 注意:确保命名空间与其他Person.cs文件中的命名空间完全匹配。
namespace SomeNamespace
{
public partial class Person
{
// Custom property (not auto-generated by Entity Framework)
public string DisplayName
{
get { return PersonID + " - " + Name + " (" + Birthdate.ToString() + ")"; }
}
}
}
非常感谢。你如何在这些属性中添加诸如'[Key]'和'[Required(ErrMessage =“”)]'这样的属性? –
这些属性在代码优先模型中更常见。首先在数据库中,您不是通过属性,而是通过模型编辑器来设置密钥。通常,EF会根据数据库结构自动确定哪些列是主键,但如果出错,您可以右键单击实体内的某个属性以更改它是否为关键。至于“必需”属性,您可以使该列不可为空,但这不会允许您设置错误消息。我建议使用IValidatableObject接口进行验证。 – TheRotag
http://www.entityframeworktutorial.net/create-poco-entity.aspx –