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

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

问题描述

EF 为我生成了一些部分类,每个类都有一个构造函数,但它说不要碰它们(下面的例子),现在如果我创建我自己的辅助部分类并且我想要一个构造函数来自动设置一些字段我该怎么做,因为它会冲突?

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

        ...
    }
}

推荐答案

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

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天全站免登陆