NullReferenceException when calling InsertOnSubmit in Linq to Sql

后端 未结 3 1696
说谎
说谎 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:56

    After doing a little research, I came to the conclusion that there's no easy way to solve this problem of submitting the inherited object directly. It's possible to Map Inheritance Hierarchies but this has nothing to do with what you pretend. You just want to submit the base class and don't care if it's actually a derived class.

    If you don't want to use a partial class to add additional properties or behavior to your table class, as suggested in the thread you mentioned, I would do a simple Clone method as a workaround:

        public partial class Audit
        {
            // ...
            public Audit Concrete()
            {
                if (this.GetType().Equals(typeof(Audit)))
                    return this;
                else
                {
                    Audit audit = new Audit();
                    // clone properties
                    return audit;
                }
            }
        }
    
    //...
    dataContext.Audits.InsertOnSubmit(audit.Concrete());
    

提交回复
热议问题