EF 5模型第一部分类自定义构造函数如何? [英] EF 5 Model First Partial Class Custom Constructor How To?
问题描述
// ------------ -------------------------------------------------- ----------------
//< auto-generated>
//该代码是从模板生成的。
//
//手动更改此文件可能会导致应用程序出现意外的行为。
//如果重新生成代码,则对该文件的手动更改将被覆盖。
//< / auto-generated>
// -------------------------------------------- ----------------------------------
命名空间Breakdown.Models
{
using System;
使用System.Collections.Generic;
public partial class调用
{
public Call()
{
this.Logs = new HashSet< Log>();
}
...
}
}
部分方法可以帮助您在这里,在T4模板中定义一个无身体部分方法并在构造函数内部调用。
public<#= code.Escape(entity)#>()
{
。 ..
OnInit();
}
partial void OnInit();
然后在您的部分类中定义部分方法并放置在构造函数中要执行的操作。如果你不想做任何事情,那么你不需要定义部分方法。
partial class Entity()
{
partial void OnInit()
{
//构造函数
...
}
}
http://msdn.microsoft.com/en-us/library/vstudio/6b0scde8.aspx
EF has generated for me some partial classes, each with a constructor, but it says not to touch them (example below), now if I make my own secondary partial class and I want to have a constructor that automatically sets some of the fields how do I do so as it would conflict?
//------------------------------------------------------------------------------
// <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 Breakdown.Models
{
using System;
using System.Collections.Generic;
public partial class Call
{
public Call()
{
this.Logs = new HashSet<Log>();
}
...
}
}
Partial methods can help you here, in the T4 Templates define a body-less partial method and call that inside the constructor.
public <#=code.Escape(entity)#>()
{
...
OnInit();
}
partial void OnInit();
Then in your partial class define the partial method and place inside that what you want to do in the constructor. If you don't want to do anything then you don't need to define the partial method.
partial class Entity()
{
partial void OnInit()
{
//constructor stuff
...
}
}
http://msdn.microsoft.com/en-us/library/vstudio/6b0scde8.aspx
这篇关于EF 5模型第一部分类自定义构造函数如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!