简体   繁体   English

删除LINQ to SQL记录而不先加载它

[英]Delete a LINQ to SQL record without loading it first

Is it possible to get LINQ to SQL to delete a record using the PK, without loading the record first? 是否有可能让LINQ to SQL使用PK删除记录,而不首先加载记录? Similar to NHibernate's proxy object functionality? 类似于NHibernate的代理对象功能?

You should be able to do it this way: 你应该能够这样做:

var person = new Person();
person.ID = someID;

using (var context = new DataContext(connString))
{
    context.Persons.Attach(person, false); //attach is as unmodified
    context.Persons.DeleteOnSubmit(person); //remove it
    context.SubmitChanges(); //submit changes to db
}

Adding to Joseph's answer: 除了约瑟夫的回答:

You may have trouble deleting in this manner if your entity has any fields for which UpdateCheck is set to Always, unless you set such fields as appropriate. 如果您的实体具有UpdateCheck设置为Always的任何字段,则可能无法以此方式删除,除非您根据需要设置此类字段。

Also, if you are deleting multiple related entities where FK constraints are involved, you may have trouble if the entities are not deleted in the proper sequence (resulting in a constraint violation). 此外,如果要删除涉及FK约束的多个相关实体,如果未按正确顺序删除实体(导致约束违规),则可能会遇到问题。 To avoid this, set all fields involved in such FKs as appropriate. 为避免这种情况,请根据需要设置此类FK中涉及的所有字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM