开发者

Derived class causes InsertOnSubmit() to throw NullReferenceException

I did look at the related posts that were answered, but still get the NullReference exception in InsertOnSubmit().

I have an auto generated LINQ class Transaction from which I create a derived class that overrides ToString():

public partial class MyTransaction:DataAccess.Transaction
{
    public MyTransaction():base()
    {

    }

    public override string ToString()
    {

        return "some text";
    }

}   

And the insert is as follows:

public bool InsertTransaction(Transaction t)
    {
        using (MarketPricesDataContext dataContext = new MarketPricesDataContext(connectionString))
        {
            try
            {                
                dataContext.Transaction.InsertOnSubmit(t);
                dataContext.SubmitChanges();
                return true;
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
                return false;
            }
        }

    }

I thought calling the base constructor from MyTransaction would solve my problem, but it did not. I can insert Transaction items but when I try to insert a MyTransaction item I get a NullReferenceExcept开发者_开发技巧ion.

This works:

Transaction t=new Transaction();
t.Type="A"; //set some values
Data d=new Data();
d.InsertTransaction(t);

This throws a NullReferenceException (Object reference not set to an instance of an object.) in InsertOnSubmit():

MyTransaction myt=new MyTransaction();
myt.Type="A"; //set some values
Data d=new Data();
d.InsertTransaction(myt as Transaction);

What am I doing wrong?


LINQ-to-SQL already supports inheritance, but only for types in the model. I imagine it is looking for your custom type in the model (to find the appropriate table or discriminator), and failing.

In short, I don't think you can use subtypes that aren't part of the model.

However, the types are partial; you should be able to do:

namespace MyTransaction:DataAccess {
    partial class Transaction {
        public override string ToString() {
            return "some text";
        }
    }  
}

which adds your ToString() override into the generated type.


Thanks Marc for pointing me in the right direction. To solve the problem, I did away with the MyTransaction class and in the DataAccess namespace, the one containing the DataContext and Linq-to-SQL classes, I override ToString() as follows:

namespace DataMining.DataAccess
{
public partial class Transaction
{
    public override string ToString()
    {
      return "some text";
    }

}
}

I now use Transaction where I before would have used MyTransaction.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜