答案 0 :(得分:0)
从数据库生成模型时(这里似乎是这种情况),会创建几个不同的代码文件。要获取上下文的代码,请展开ProgramMasterList.Context.tt
。您将在其中看到上下文类的.cs文件。
然后,对于从数据库中选择的每个表作为模型的一部分,将创建一个实体类。您可以通过展开ProgramMasterList.tt
找到这些内容。例如,如果您有一个名为Person的表,则可能有一个实体类文件Person.cs
,其中定义了Person
类。
现在,您提到要修改类以添加属性。如果您修改ProgramMasterList.tt
下由实体框架动态生成的类文件,那么下次从数据库更新模型时(例如将数据库中的新表添加到模型中),您所做的更改将被覆盖。幸运的是,这是一个更好的方法。 ProgramMasterList.tt
下的每个类都是部分类。因此,您可以在不修改Entity Framework自动生成的文件的情况下添加到该类。只需创建一个新文件,声明Person类(部分),然后在其中添加额外的方法,属性等。我建议把所有这些"扩展"进入一个文件夹,以保持他们的组织,但这取决于你。
所以,它可能看起来像这样:
解决方案结构:
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; }
}
}
Person.cs(在Extensions文件夹中) 注意:确保命名空间与其他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() + ")"; }
}
}
}