Skip to main content
 首页 » 编程设计

C# 类构造函数分配给 'this'

2024年02月05日12sxdcgaq8080

我有一个“天真的”问题。

使用以下示例代码:

public class ThisClass 
{ 
    public int ThisClassID { get; set; } 
    public string ThisValue { get; set;} 
 
    public ThisClass() 
    { 
    } 
 
    public ThisClass(int thisClassID) 
    { 
        using (MyContext dbContext = new MyContext()) 
        { 
            this = dbContext.CaseNotes.Find(thisClassID); 
        } 
    } 
} 

当然,我收到错误消息 Cannot assign to 'this' because it is read-only

我所知道的解决这个问题的唯一两种方法是使用静态方法,或者分别分配给每个属性。

有没有办法创建一个简单的构造函数,将数据库实体返回到 this 中?

更新 以下两个答案都是正确,但我只能接受一个。有一些关于工厂和存储库模式的使用的有趣讨论,当潜在的答案被删除时,这些模式很遗憾地被删除了。赞成和反对的论点相当平衡,有人指出 Entity Framework 本身是一个使用存储库模式的工厂。问题本身有 3 票赞成票和 2 票反对票。

答案似乎没有单一的答案。

请您参考如下方法:

你应该看看AutoMapper ,您的代码可能如下所示:

// Somewhere in your application/service initialization class and in some method... 
Mapper.CreateMap<ThisClass, ThisClass>(); 
 
public class ThisClass 
{ 
    public int ThisClassID { get; set; } 
    public string ThisValue { get; set;} 
 
    public ThisClass() 
    { 
    } 
 
    public ThisClass(int thisClassID) 
    { 
        using (MyContext dbContext = new MyContext()) 
        { 
            Mapper.Map(dbContext.CaseNotes.Find(thisClassID), this); 
        } 
    } 
} 

顺便说一句,这听起来像是个坏主意。我不会在其自己的构造函数中填充域对象。

这是一份很好的责任for the repository .