4

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.

2 Answers 2

4

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 (set UpdateCheck="Never" on all the interesting columns in the dbml).

However, perhaps a simpler option is:

_context.ExecuteCommand("delete from [TableName] where [PrimaryKey]={0}", id);

or something along those lines. Not object oriented, but very effective. Note that this doesn't run in the same transaction as SubmitChanges unless 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.

Sign up to request clarification or add additional context in comments.

2 Comments

@Luke beware: that will mean you don't get concurrency checks on your updates, too.
that should be fine I'm actually only using it for a performance test anyway and validating state aftewards
0

Try to change

public DateTime TestDate { get; set; }

to

public DateTime? TestDate { get; set; }

And set this field NULLable in your database table

2 Comments

I want to do this without setting this as nullable. I shouldnt have to change my model to make it fast to delete
OK, you haven't noticed about that. What about changing default value of the field in datamodel or orm layer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.