views:

44

answers:

1

I am using LINQ to SQL with single table inheritance for an audit log. There is a field/property called Type that i am using as the dicriminator and i have created a base type and a single inherited type (there will be more later if i can actually get this to work).

So that i don't have to write a different method to insert each different derived audit type the method takes the base type, but it doesn't work, it throws a SQLTypeException saying that the date is out of range, despite the fact that the only date field has been set using DateTime.Now. I have written some basic debugging code and found a strange effect. The below code works fine:

tOnHoldReasonAudit dbAudit = new tOnHoldReasonAudit();
dbAudit.ApplicationID = 1;
dbAudit.Date = DateTime.Now;
dbAudit.UserID = 9;
pi_DataContext.tApplicationAudits.InsertOnSubmit(dbAudit);
pi_DataContext.SubmitChanges();

However if i change the first line to

tApplicationAudit dbAudit = new tOnHoldReasonAudit();

where tApplicationAudit is the base type it throws the exception, specifically:

System.Data.SqlTypes.SqlTypeException: SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM.

Why does this not work, what exactly is going on here. In my live code i have a method AddAudit(tApplicationAudit Audit) that does the actual work, i don't want to have to write an add method for each different derived type as this defeats the whole object, if i have to do that i might as well do away with the derived audit types and just set the type property on the base class.

Update:

Below is the initial part of the class definitions for the LinqTSql audit types that was created by O/R designer:

[Table(Name="dbo.tApplicationAudit")]
[InheritanceMapping(Code="1", Type=typeof(tOnHoldReasonAudit), IsDefault=true)]
public partial class tApplicationAudit : INotifyPropertyChanging,INotifyPropertyChanged

public partial class tOnHoldReasonAudit : tApplicationAudit
A: 

I figured this out. It was because the properties on the derived type were simply hiding the coresponding properties on the base type. When i changed the properties on the base type to virtual and the override on the derived type, it fixed it. I think linq to sql must have been casting it back to the derived type to access the data.

Ben Robinson