C#类构造函数分配给“ this” [英] C# class constructor assigning to 'this'

查看:95
本文介绍了C#类构造函数分配给“ this”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个天真问题。

具有以下示例代码:

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);
        }
    }
}

当然,我得到错误由于它是只读的而无法分配给'this'

解决此问题的仅有两种方法我知道有一个静态方法,或分别分配给每个属性。

The only two ways of solving this that I know of are to have a static method, or to assign to each property separately.

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

Is there any way of creating a simple constructor that returns database entities into this?

更新
以下两个答案都是正确,但我只能接受一个。关于工厂和存储库模式的使用,进行了一些有趣的讨论,但是当删除潜在答案时,不幸地删除了工厂和存储库模式。有人指出,论证在论证上是平等的,两者都是平衡的。Entity Framework本身是使用存储库模式的工厂。这个问题本身有3个投票和2个投票。

UPDATE Both answers below are correct but I can only accept one. There was some interesting discussion on the use of factories and repository patterns that were sadly deleted when a potential answer was deleted. Arguments were equally balanced both for and against with some pointing out the the Entity Framework itself is a factory that uses a repository pattern. The question itself had three upvotes and two downvotes.

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

The answer seems to be that there is no single answer.

推荐答案

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

You should take a look at AutoMapper, and your code could look as follows:

// 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);
        }
    }
}

顺便说一句,听起来很糟糕理念。我不会在其自己的构造函数中填充域对象。

BTW it sounds like a bad idea. I wouldn't populate a domain object inside its own constructor.

这是很好的责任存储库

这篇关于C#类构造函数分配给“ this”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆