NullReferenceException when calling InsertOnSubmit in Linq to Sql

后端 未结 3 1720
说谎
说谎 2021-01-15 09:05

I\'m trying to insert a new object into my database using LINQ to SQL but get a NullReferenceException when I call InsertOnSubmit() in the code snippet below. I\'m passing i

3条回答
  •  悲&欢浪女
    2021-01-15 09:50

    Try creating a base abstract class that has only properties ID and typeDiscriminator; after that create the concrete class that inherits from the base and eventually other classes that inherits from the last one. Don't include properties in derived classes that are already presents in base one.

    Example: Assuming a base abstract class named BasePeoples that has properties ID and typeDiscriminator, we have a class of type Person that inherits from the base and two other classes of type Fisherman and Driver that inherits form Person.

    So you'll be able to do something like this

    using (DatabaseDataContext db = new DatabaseDataContext())
            {
                Person p = new Person();
                p.FirstName = "Dario";
                p.LastName = "Iacampo";
    
                Fisherman f = new Fisherman();
                f.FirstName = "San";
                f.LastName = "Pei";
                f.CollectedFishes = 10;
                f.FishingLicenceNumber = "abc";
    
                Driver d = new Driver();
                d.FirstName = "Michael";
                d.LastName = "Shumaker";
                d.CarMake = "Ferrari";
                d.DrivingLicenceNumber = "123abc";
    
                db.BasePeoples.InsertOnSubmit(f);
                db.BasePeoples.InsertOnSubmit(d);
                db.SubmitChanges();
    
            }
    

提交回复
热议问题