简体   繁体   中英

C# class constructor assigning to 'this'

I have a 'naïve' question.

With the following sample code:

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.

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

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.

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

In practice no. In theory you can make the type a struct . Then, the code should compile. You can assign to this in a struct.

Probably, you should not use a constructor at all. Create a factory method that simply returns the result from Find.

One unchangeable fact about constructors is that they create a fresh object every time. I don't think you want that here. You probably want to preserve the existing object instance and its identity.

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.

This is a good responsibility for the repository .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM