【问题标题】:Adding new constructors to entity向实体添加新的构造函数
【发布时间】:2012-09-16 11:14:29
【问题描述】:

我正在使用 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; }
}

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

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

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

【问题讨论】:

    标签: c# .net entity-framework partial-classes


    【解决方案1】:

    EF(数据库优先或模型优先)创建这些默认构造函数...

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

    ...仅作为实例化导航集合的助手,以保护您免受NullReferenceExceptions 的侵害。但这不是必需的。如果您从数据库加载 User 实体,包括 BookmarkedDealsBookmarkedStores EF 无论如何都会实例化集合。如果您自己创建 User,如果构造函数不存在,您只需要手动实例化集合:

    var user = new User { BookmarkedDeals = new HashSet<BookmarkedDeal>() };
    user.BookmarkedDeals.Add(new BookmarkedDeal());
    

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

    public User(SomeType SomeParameter) : this()
    {
        //Do somthing with SomeParameter...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-01
      • 2012-12-13
      • 2015-10-16
      • 1970-01-01
      相关资源
      最近更新 更多