views:

477

answers:

2

In my database I have a table called StaffMembers

when I bring this into my .net Project as through linq-to-sql an entity class StaffMember is created

Now I have also created a partial class StaffMember in my project also, to add extra properties that I use in other top layers. eg. IsDeleted property. This partial class also inherits an abstract class and interface to make sure some other properties are also implemented.

Now when I create a new instance of "StaffMember"

eg. StaffMember newStaff = new StaffMember(); and give it all its properties etc

and then call the InsertOnSubmit on the context through my Manager.

Add(StaffMember newStaff)
{
     context.StaffMembers.InsertOnSubmit(newStaff);
     context.Save();
}

I get an "Object reference not set to an instance of an object" error.

on context.StaffMembers.InsertOnSubmit(newStaff);

The stack says

"   at System.Data.Linq.Mapping.EntitySetDefSourceAccessor`2.GetValue(T instance)\r\n   at 
System.Data.Linq.Mapping.MetaAccessor`2.GetBoxedValue(Object instance)\r\n   at 
System.Data.Linq.ChangeTracker.StandardChangeTracker.StandardTrackedObject.HasDeferredLoader(MetaDataMember deferredMember)\r\n   at 
System.Data.Linq.ChangeTracker.StandardChangeTracker.StandardTrackedObject.get_HasDeferredLoaders()\r\n   at 
System.Data.Linq.ChangeTracker.StandardChangeTracker.Track(MetaType mt, Object obj, Dictionary`2 visited, Boolean recurse, Int32 level)\r\n   at 
System.Data.Linq.ChangeTracker.StandardChangeTracker.Track(Object obj, Boolean recurse)\r\n   at 
System.Data.Linq.ChangeTracker.StandardChangeTracker.Track(Object obj)\r\n   at System.Data.Linq.Table`1.InsertOnSubmit(TEntity entity)\r\n   at 
BusinessObjects.StaffMemberManager.Add(StaffMember staffMember) in     
C:\\StaffMemberManager.cs:line 251"

Any idea why would this be happening and what's the way around it.

Thanks

+11  A: 

Alright I found my answer on http://social.msdn.microsoft.com/Forums/en/linqprojectgeneral/thread/0cf1fccb-6398-4f16-920b-adef9dc4ac9f

in case some is still looking for an answer.

This problem happens when you overload the constructor in the partial class, and not call the default constructor in it.

The default constructor of the entity does few things thats required by the Context object.

Hence if you have an overloading constructor in your partial class and using it to create the object, make sure the default constructor is called in the first line

in C# you can do this by

eg.

 Customer(string custID)

you need to add a

 Customer(string custID):this()

in C# where Customer is my class and Customer(string custID):this() is my overload constructor in my partial class.

soldieraman
+1 Solved my problem! Thanks for the post!!
Alexander
A: 

Sometime, just forgot to add this line to the base class:

[InheritanceMapping(Code = "Class", Type = typeof(Class))]

Eric