C# class constructor assigning to 'this'

前端 未结 2 1252
迷失自我
迷失自我 2021-01-21 18:13

I have a \'naïve\' question.

With the following sample code:

public class ThisClass
{
    public int ThisClassID { get; set; }
    public string ThisValu         


        
相关标签:
2条回答
  • 2021-01-21 18:35

    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.

    0 讨论(0)
  • 2021-01-21 18:38

    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.

    0 讨论(0)
提交回复
热议问题