LINQ-to-SQL +一对多+ DataBinding删除 [英] LINQ-to-SQL + One-to-Many + DataBinding deleting

查看:96
本文介绍了LINQ-to-SQL +一对多+ DataBinding删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用LINQ-to-SQL从具有一对多关系的两个表的数据库中加载数据(一个食谱有很多成分).

I use LINQ-to-SQL to load data from a database that has two tables in a one-to-many relationship (one Recipe has many Ingredients).

我加载配方,LINQ将成分对象检索到绑定到ListBox的EntitySet中.

I load a Recipe and LINQ retrieves Ingredient objects into an EntitySet that is binded into a ListBox.

如果我想从配方中删除一些配料,则会收到试图删除配方和配料之间的关系.但是,该关系的外键之一(Ingredient.RecipeID)不能设置为

If I want to delete some Ingredients off a Recipe, I get a "An attempt was made to remove a relationship between a Recipe and a Ingredient. However, one of the relationship's foreign keys (Ingredient.RecipeID) cannot be set to null.

我使用众所周知的解决方案通过将'DeleteOnNull ="true"'添加到DBML文件来解决了这个问题.但是,仅当我们删除从数据库中检索到的成分对象时,添加此设置才可以解决问题.

I SOLVED this problem using the well known solution by adding 'DeleteOnNull="true"' to the DBML file. But adding this setting only removes the problem when we are deleting Ingredient objects that were retrieved from the DB.

问题在于在代码中创建的成分对象(添加到配方中),并添加到成分的EntitySet集合中,然后在调用SubmitUpdates之前将其删除.然后,再次发生相同的异常.当用户向其中添加成分,出错并从配方中删除成分时,通常会在未保存的新配方上发生这种情况.我在DBML的两个"Association Name ="Recipe_Ingredient""行中都添加了DeleteOnNull.

The problem is with the Ingredient objects that were created in code (added to a Recipe) and added to the EntitySet collection of Ingredients and then deleted BEFORE SubmitUpdates is called. Then, the same exception happens again. This usually happens on a new, unsaved recipe when user is adding ingredients to it, makes a mistake and erases an ingredient off a recipe. I added the DeleteOnNull to both 'Association Name="Recipe_Ingredient"' lines in DBML.

我应该如何删除此类对象?我目前看到的唯一解决方案是,我将配料加载到不在DataContext下的集合中,然后在保存时从配方中删除所有配料,然后从该缓存中再次添加.

How am I supposed to remove such objects? The only solution I see at the moment is that I would load the ingredients into a collection not under the DataContext and then when saving, delete all ingredients off a recipe and add then again from that cache..

推荐答案

        try
        {
            // Needed for existing records, but will fail for new records
            yourLINQDataContext.Ingredients.DeleteOnSubmit(ingredient);
        }
        catch (Exception)
        {
            // Swallow
        }

        yourRecipeObject.Ingredients.Remove(ingredient);

这篇关于LINQ-to-SQL +一对多+ DataBinding删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆