Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Parameterized/Overloaded Constructors?

I've seen similar questions but they aren't quite what I am referring to (or maybe they are and I don't understand the answers)

In my previous application using Linq2SQL I was able to overload constructors with parameters by doing this:

Namespace CoreDb    
  Partial Public Class Accomplishment

    Public Sub New(ByVal accomplishmentTypeID As Object, ByVal description As String, ByVal title As String, ByVal applicableDate As DateTime, ByVal lastUpdatedBy As String)
        Me.New()

        If TypeOf (accomplishmentTypeID) Is Guid Then
            Me.AccomplishmentTypeId = accomplishmentTypeID
        End If

        If TypeOf (accomplishmentTypeID) Is String Then
            Me.AccomplishmentTypeId = New Guid(accomplishmentTypeID.ToString())
        End If

        Me.Description = description
        Me.ApplicableDate = applicableDate
        Me.Title = title
        Me.Id = Guid.NewGuid()
        Me.DateCreated = DateTime.Now
        Me.DateModified = DateTime.Now
        Me.LastUpdatedBy = lastUpdatedBy
        Me.CreatedBy = lastUpdatedBy
    End Sub
 End Class
End Namespace

Basically using a partial class off the object, sharing the namespace of the .dbml file and calling the default constructor and then doing additional stuff.

So then in my code I could do something like:

Dim accomplishment As New Accomplishment(id, description, title, applicableDate, lastUpdatedBy)

This seems to no longer work in Entity Framework as there is no default constructor to call.

Does this no longer work? And if so what is a good alternative to implementing something like this?

like image 970
SventoryMang Avatar asked Mar 17 '11 16:03

SventoryMang


1 Answers

There is not any default constructor generated, but that doesn't mean it has none. But when you define a constructor with parameters in a class that has no parameterless constructor explicitly set, it will hide the default one.

So in you partial class you just need to also define a parameterless constructor.

like image 137
František Žiačik Avatar answered Sep 29 '22 07:09

František Žiačik