EF 5模型第一部分类自定义构造函数如何? [英] EF 5 Model First Partial Class Custom Constructor How To?

查看:216
本文介绍了EF 5模型第一部分类自定义构造函数如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  // ------------ -------------------------------------------------- ---------------- 
//< 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆