我需要使用数据库优先方法覆盖或替换项目模型的默认构造函数。经过一些研究,我发现这个答案最适合我完成我想要的工作:
Override or replace default constructor when using database first approach
.
所以,作为一个专家,我去了我的projectmodel.edmx,在里面我发现了两个扩展名为.tt的文件,它们被称为
ProjectModel.Context.tt
和
ProjectModel.tt
,所以我想我需要编辑第二个。
为了理解这是如何工作的,我找到了一段代码,它似乎生成了类的构造函数:
1 <#
2 var complexProperties = typeMapper.GetComplexProperties(complex);
3 var propertiesWithDefaultValues = typeMapper.GetPropertiesWithDefaultValues(complex);
4
5 if (propertiesWithDefaultValues.Any() || complexProperties.Any())
6 {
7 #>
8 public <#=code.Escape(complex)#>()
9 {
10 <#
11 foreach (var edmProperty in propertiesWithDefaultValues)
12 {
13 #>
14 this.<#=code.Escape(edmProperty)#> = <#=typeMapper.CreateLiteral(edmProperty.DefaultValue)#>;
15 <#
16 }
17
18 foreach (var complexProperty in complexProperties)
19 {
20 #>
21 this.<#=code.Escape(complexProperty)#> = new <#=typeMapper.GetTypeName(complexProperty.TypeUsage)#>();
22 <#
23 }
24 #>
25 Init();
26 }
27
28 partial void Init();
29
30 <#
31 }
我添加了第25行和第28行,只是为了使用对init()的调用生成模型,然后声明方法。
现在,我去了
ProjectModel.edmx
它显示了我的数据库的图表,我右键单击图表并运行
从数据库更新模型…
《男人》杂志。然后我去了
刷新
选项卡并突出显示
桌子
点击
完成
. 我希望新生成的文件与此类似:
namespace Project.Models.DB
{
using System;
using System.Collections.Generic;
public partial class Class1
{
public Class1()
{
this.Events = new HashSet<Event>();
Init();
}
partial void Init();
public int id { get; set; }
public string name { get; set; }
public string slug { get; set; }
public bool is_active { get; set; }
public System.DateTime date_created { get; set; }
public System.DateTime date_updated { get; set; }
public virtual ICollection<Event> Events { get; set; }
}
}
但是它不起作用,我想知道我是否需要做其他的事情,或者我是否在编辑正确的文件。任何指导都将不胜感激。