EF 5 Model First Partial Class Custom Constructor如何?

spr*_*t12 10 constructor entity-framework partial-classes ef-model-first

EF已经为我生成了一些部分类,每个都有一个构造函数,但它表示不要触摸它们(下面的示例),现在如果我创建自己的辅助部分类并且我想要一个构造函数自动设置一些字段如何我会这样做,因为它会发生冲突吗?

//------------------------------------------------------------------------------
// <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>();
        }

        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*ael 20

部分方法可以在这里帮助您,在T4模板中定义一个无体的局部方法并在构造函数中调用它.

public <#=code.Escape(entity)#>()
{
    ...
    OnInit();
}

partial void OnInit();
Run Code Online (Sandbox Code Playgroud)

然后在您的partial类中定义partial方法,并在构造函数中放置您想要执行的操作.如果您不想做任何事情,那么您不需要定义部分方法.

partial class Entity()
{
    partial void OnInit()
    {
        //constructor stuff
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

http://msdn.microsoft.com/en-us/library/vstudio/6b0scde8.aspx


Sam*_*ath 1

这不可能。

部分类本质上是同一类的一部分。

任何方法都不能被定义两次或被覆盖(相同的规则也适用于构造函数)

但您可以使用下面提到的解决方法:

//From file SomeClass.cs - generated by the tool
public partial class SomeClass
 {
    // ...
 }


// From file SomeClass.cs - created by me
public partial class SomeClass
  {
    // My new constructor - construct from SomeOtherType
    // Call the default ctor so important initialization can be done
    public SomeClass(SomeOtherType value) : this()
      {

       }
  } 
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看部分类、默认构造函数

我希望这对你有帮助。