向实体添加新构造函数

dot*_*oob 4 .net c# entity-framework partial-classes

我正在使用EF4.3.这是我的第一个项目,所以我一直在学习.

有些情况下我需要为实体建立额外的构造函数.我创建了一个额外的部分类来执行此操作,因此实体用户将具有关联的类User2.

我注意到EF总体上不会创建构造函数,但是有这样的实例:

public partial class User
{
    public User()
    {
        this.BookmarkedDeals = new HashSet<BookmarkedDeal>();
        this.BookmarkedStores = new HashSet<BookmarkedStore>();
    }

    public System.Guid UserId { get; set; }
    public int UserStatusId { get; set; }
    public int UserRoleId { get; set; }
    public System.DateTime CreatedOn { get; set; }
    public System.DateTime LastVisitedOn { get; set; }

    public virtual ICollection<BookmarkedDeal> BookmarkedDeals { get; set; }
    public virtual ICollection<BookmarkedStore> BookmarkedStores { get; set; }
    public virtual Subscriber Subscriber { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这让我有点担心,因为它很容易通过设计器添加导航属性,基础构造函数中的代码错过了.

    public User()
    {
        this.BookmarkedDeals = new HashSet<BookmarkedDeal>();
        this.BookmarkedStores = new HashSet<BookmarkedStore>();
    }
Run Code Online (Sandbox Code Playgroud)

我的问题是,我是否需要从我的其他构造函数中调用基础构造函数,我是否应该将代码(:this User())在所有情况下调用我的基础构造函数作为安全措施?

Sla*_*uma 6

EF(Database First或Model First)创建那些默认构造函数......

public User()
{
    this.BookmarkedDeals = new HashSet<BookmarkedDeal>();
    this.BookmarkedStores = new HashSet<BookmarkedStore>();
}
Run Code Online (Sandbox Code Playgroud)

...仅作为帮助实例化导航集合以保护您一点点对抗NullReferenceExceptions.但这不是必需的.如果User从数据库加载实体,包括BookmarkedDealsBookmarkedStoresEF,无论如何都将实例化集合.如果您User自己创建,则只需在构造函数不存在的情况下手动实例化集:

var user = new User { BookmarkedDeals = new HashSet<BookmarkedDeal>() };
user.BookmarkedDeals.Add(new BookmarkedDeal());
Run Code Online (Sandbox Code Playgroud)

如果你添加一个新的构造函数,我会调用默认的构造函数,使集合的实例化在所有构造函数之间保持一致.但我认为它必须是this,不是base因为两个构造函数都在同一个类中,而不是在继承层次结构中:

public User(SomeType SomeParameter) : this()
{
    //Do somthing with SomeParameter...
}
Run Code Online (Sandbox Code Playgroud)