Linq to SQL: insert subclassed row

J

JS

Using Linq to work with an SQL database has worked out well so far,
however I had a problem recently where I wanted to subclass one of the
auto-generated table classes. I'd like to be able to insert an
instance of the subclass into the table, but an exception is thrown.

I'm not at my dev computer right now, so I don't have the exception
details but I wondered if anyone knew why we can't do this or what I
need to do to insert an instance of a subclass.

Thanks.
 
M

Marc Gravell

Does the data-context know about the subclass? i.e. via a
discriminator? LINQ-to-SQL is very specific about types; you can't
arbitrarily use your own subclasses if the data-context doesn't expect
it - it wouldn't be able to re-create it, for instance, and thus there
would be identity management issues if you added such an item and then
searched for it via a query.

Marc
 
J

JS

Does the data-context know about the subclass? i.e. via a
discriminator?
No, other than the fact that my class is effectively an instance of
the base class which the data context does know about. And I'll have
to look up what a discriminator is so I can't answer the 2nd part of
your question.

I don't quite understand why Linq to SQL does not allow this. If I
wanted to query for my item, I would expect an instance of the base
class to be returned.

Luckily my current application is not performance critical in this
part of the app, so I can clone my subclass instance as the base class
and add it to the db.
 
M

Marc Gravell

Basically, LINQ-to-SQL also allows inheritance, and allows (for example)
the class of a type to map to a column - the "discriminator". So if you
have a table:

Customers
ID Type ....etc...
1 R ....
2 S ....
3 R ....

you can map your customers with "Type=S" to your SuperCustomer type, and
leave your regular customers "Type=R" mapped to your Cutomer type. The
data-context knows how to handle this for both querying and saving data.

This means that when a data-context is given an object, it looks at the
type to understand how to handle the record.

Another perspective here is that the whole point of an ORM is that if
you put something in, you can get it back again. In your scenario, if
you give it a subclass instance that it isn't expecting, then the
data-context *knows* that it can't possibly ever give it you back (in
the same form), so it is (quite reasonably) refusing to handle that object.

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top