C#类构造器中分配给'这' [英] C# class contructor assigning to 'this'

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

问题描述

我有一个幼稚的问题。

通过下面的示例代码:

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

和,当然,我得到的错误无法分配给'这',因为它是只读

And, of course, I get the error Cannot assign to 'this' because it is read-only

只有两个解决这一途径我所知道的是有一个静态方法,或分配给单独的每个属性。

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

有没有创建一个简单的构造函数,返回数据库实体到<$的任何方式C $ C>这个?

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

更新
下面两个答案都的正确但我只能接受一个。有对使用工厂和库模式,当一个潜在的答案被删除了那名不幸的是删除了一些有趣的讨论。 Arguements分布也同样均衡支持和反对双方的一些指明了实体框架本身是使用存储库模式的工厂。这个问题itselft有三个upvotes和两个downvotes。

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. Arguements 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 itselft 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这听起来像一个坏理念。我不会填充自己的构造内部的域对象。

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

这是一个不错的责任的存储库

This is a good responsibility for the repository.

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

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