Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF 5 Model First Partial Class Custom Constructor How To?

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

        ...
    }
}
like image 521
sprocket12 Avatar asked Jan 23 '13 16:01

sprocket12


2 Answers

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

like image 53
Michael Avatar answered Nov 11 '22 22:11

Michael


This is not possible.

Partial classes are essentially parts of the same class.

No method can be defined twice or overridden (same rule apply for the constructor also)

But You can use below mentioned Workaround :

//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()
      {

       }
  } 

for more information check Partial Classes, Default Constructors

I hope this will help to you.

like image 20
Sampath Avatar answered Nov 11 '22 21:11

Sampath