I am wanting to remove an entity from a database using LINQ2SQL without having to pre-fetch it (for performance reasons).
I undersand that this can be done as follows(Delete a LINQ to SQL record without loading it first ):
public void Delete(int id)
{
var e = new TestEntity { Id = id };
_context.TestEntities.Attach(e, false);
_context.TestEntities.DeleteOnSubmit(e);
}
however when TestEntity contains a datetime similar to:
public class TestEntity
{
public int Id { get; set; }
public String TestString { get; set; }
public DateTime TestDate { get; set; }
public int TestInt { get; set; }
}
I get the following error:
SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and
12/31/9999 11:59:59 PM.
which basically means its trying to validate .net default datetime against a SQL datetime
Is there a way of deleting an entity with a non-nullable without needing to prefetch it?
*Note ive also tried setting the datetime value to a dummy one, in which case i get the following:
Row not found or changed.
The “Row not found or changed” suggests that you have those columns set for validation. If you have a timestamp (
rowversion) column, you could use that single value for optimistic concurrency checks, although you still won’t know the value, of course. In some cases, you could disable concurrency checks completely (setUpdateCheck="Never"on all the interesting columns in the dbml).However, perhaps a simpler option is:
or something along those lines. Not object oriented, but very effective. Note that this doesn’t run in the same transaction as
SubmitChangesunless you manage the transaction yourself, and that it won’t validate that exactly 1 row was deleted. But it is direct. Also note that the data-context won’t know about this change, so if your data-context also has (say) pending updates for that row it could get confused.