Jonathan Jansen
Jonathan Jansen

Reputation: 133

Entity framework database first protected constructor

How do I make my constructor protected in when using entity framework database first?

When I generate an Entity Data Model from my database, the auto generated class contains a public constructor,

//------------------------------------------------------------------------------
// <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 Domain.Models
{
    using System;
    using System.Collections.Generic;

    public partial class MyClass
    {
        public MyClass()
        {

what I would like is a protected constructor

    public partial class MyClass
    {
        protected MyClass()
        {

Upvotes: 0

Views: 1818

Answers (2)

Gert Arnold
Gert Arnold

Reputation: 109079

You can do this by modifying the t4 template that creates the model classes. Look for this part near the top of the file:

foreach (var entity in typeMapper.GetItemsToGenerate<EntityType>(itemCollection))
{
    fileManager.StartNewFile(entity.Name + ".cs");
    BeginNamespace(code);
#>
<#=codeStringGenerator.UsingDirectives(inHeader: false)#>
<#=codeStringGenerator.EntityClassOpening(entity)#>
{
<#
    var propertiesWithDefaultValues = typeMapper.GetPropertiesWithDefaultValues(entity);
    var collectionNavigationProperties = typeMapper.GetCollectionNavigationProperties(entity);
    var complexProperties = typeMapper.GetComplexProperties(entity);

    if (propertiesWithDefaultValues.Any() || collectionNavigationProperties.Any() || complexProperties.Any())
    {
#>
    public <#=code.Escape(entity)#>()
    {
<#

and replace the bottom line public <#=code.Escape(entity)#>() by

protected <#=code.Escape(entity)#>()

This change will create protected constructors for entity type. Lower in the file there is a similar construct for complex types, you may want to modify that one as well.

A word about "updates". If you update the model from the database, these changes will not be overwritten. However, if you update EF, a problem with modified t4 templates is that you have to do it again when you want to use the templates of the new version.

Upvotes: 3

phil soady
phil soady

Reputation: 11328

You cant have a protected Model constructor is incorrect. Can under circumstances - See Link provided by Gert. http://msdn.microsoft.com/en-us/library/vstudio/dd468057%28v=vs.100%29.aspx Thanks Gert for correction.

So you could via T4 change.

Do you still see that as best way to solve your problem ?

You can use something like the validation interface IValidatableObject which EF will call during save operations to verify the data is ok.

Remember when reading data, EF fills poco instances and sticks reference in a context. When you fill the POCO instance you can trigger validations when you like, ef will call validate before saving. Search google for this topic.

eg

    /// <summary>
    /// Get called everytime  a Validation is triggered on an object. EG MVC model check or  EF save.
    /// </summary>
    public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {

        // Sample Implementation. 
        var validationResult = new List<ValidationResult>();

        // a field cant be null or empty when condition X is true.
        if ( SOME CONDTION that is true   ) {
          validationResult.Add(new ValidationResult(some field is required when...", new List<string>() {"FieldName"}));
          }

        return validationResult;
    }

Upvotes: 1

Related Questions