views:

30

answers:

2

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 contructor 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 NullReferenceException. 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?

+1  A: 

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.

Marc Gravell
Yes, you have the right idea and it helped me to find the solution. I added another answer to show what I did to solve the problem in my context. Unable to give you a +1 as my reputation is less than 15.
Ewald Stieger
+1  A: 

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.

Ewald Stieger
Oops - I got the namespace wrong :)
Marc Gravell