Search code examples
c#ef-code-firstcode-first

How can I have both public and private empty constructor?


How can I have both private and public empty constructor? I need an empty private constructor, because I am doing code first with EF.

The documentation says:

Does the Entity Framework require objects with public empty constructors?

While the default generated classes have an automatically supplied public parameterless constructor, there's nothing in the framework that requires that it be public. There must be a parameterless constructor, but it can be internal or private.

My attempt:

    public class ImmediatePayment:Payment
    {
            private ImmediatePayment(){}
        
           //Problem
            public ImmediatePayment():basePayment(0){}
            
        //defining number other then 0 would make ImmediatePayment pointless, I could check the value of DeadlineDaysAfterOrder, but it seems really really nice to have a constructior without a number
            public ImmediatePayment(intDeadlineDaysAfterOrder):basePayment(DeadlineDaysAfterOrder){}
            
    }
            
public class Payment
{
      public int DeadlineDaysAfterOrder {get;private set;}
      
      private Payment(){}
      public Payment(int DeadlineDaysAfterOrder)
      {
      this.DeadlineDaysAfterOrder  = DeadlineDaysAfterOrder;
      }
}

Solution

  • The answer is, you can't have both, empty private and empty public constructors in the same class. But you don't need in this case, remove the private constructor.

    There must be a parameterless constructor, it can be internal or private. But it doesn't have to be private, it can be public which is also the default if it's generated.

    Reference: Entity Framework FAQ: Entity Classes - Does the Entity Framework require objects with public empty constructors?