How can you change a parameterless constructor without creating an Entity Framework 6 database?

In previous versions of EF (4, 5), I had the following extension for my class User

:

public partial class User {
    public User()
    {
        DateCreated = DateTime.Now;
    }
}

      

But on EF6, code generation creates a class with a parameterless constructor already given without parameters and as such I get the following compile-time error:

The type "Core.Models.User" already defines a member named "User" with the same parameters

How can I ensure the value is initialized DateCreated

when building with an EF6 database - first? More generally: how can I create my own parameterless constructor in EF6 * classes?

EDIT: Here's the cited version of the autogenerated class for reference:

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

    public partial class User
    {
        public User()
        {
            this.Nodes = new HashSet<Node>();
            this.UserOpenIDs = new HashSet<UserOpenID>();
            this.Flags = new HashSet<Flag>();
            this.AwardedMedals = new HashSet<AwardedMedal>();
        }

        public int UserID { get; set; }
        public string Email { get; set; }
        public string DisplayName { get; set; }
        public System.DateTime DateCreated { get; set; }
        public string Location { get; set; }
        public string RealName { get; set; }

        public virtual ICollection<Node> Nodes { get; set; }
        public virtual ICollection<UserOpenID> UserOpenIDs { get; set; }
        public virtual ICollection<Flag> Flags { get; set; }
        public virtual ICollection<AwardedMedal> AwardedMedals { get; set; }
    }
}

      

+3


source to share


1 answer


You cannot implement a second parameterless constructor User()

because there is already one in the autogenerated class.

Hence, you only have 2 options for solving this problem:

  • Inherit from the original class User

    (see below).

  • Modify the T4 template so the parameterless constructor is generated with the added code DateCreated = DateTime.Now;

    you want to add. This will generate additional code every time you update your data model from the database.



If you want to select option 1, do it as shown below:

public class myUser: User 
{
    public myUser(): base()
    {
        DateCreated = DateTime.Now;
    }
}

      

NB: You will need to use casting to support your myUser class.

+1


source







All Articles