DLINQ-在没有 .InsertOnSubmit(...) 的情况下插入实体?

发布于 2024-07-10 13:15:57 字数 727 浏览 8 评论 0原文

我在使用 DLINQ 时遇到了一个有趣的问题。 当我实例化一个实体时,在 DataContext 上调用 .SubmitChanges() 将在数据库中插入一个新行 - 而无需调用 .Insert[All]OnSubmit(...)。

//Code sample:
Data.NetServices _netServices = new Data.NetServices(_connString);

Data.ProductOption[] test = new Data.ProductOption[]
{
        new Data.ProductOption
        {
             Name="TEST1", 
             //Notice the assignment here
             ProductOptionCategory=_netServices.ProductOptionCategory.First(poc => poc.Name == "laminate")
        }
};

    _netServices.SubmitChanges();

运行上面的代码将在数据库中插入一个新行。 我在编写一个应用程序来解析 XML 文件并填充一些表时注意到了这种效果。 我注意到有 1000 多个插入,而我只期望大约 50 个左右 - 然后我终于隔离了这种行为。

如何防止这些对象被隐式持久化?

谢谢, ——查尔斯

I ran into an interesting problem while using DLINQ. When I instantiate an entity, calling .SubmitChanges() on the DataContext will insert a new row into the database - without having ever called .Insert[All]OnSubmit(...).

//Code sample:
Data.NetServices _netServices = new Data.NetServices(_connString);

Data.ProductOption[] test = new Data.ProductOption[]
{
        new Data.ProductOption
        {
             Name="TEST1", 
             //Notice the assignment here
             ProductOptionCategory=_netServices.ProductOptionCategory.First(poc => poc.Name == "laminate")
        }
};

    _netServices.SubmitChanges();

Running the code above will insert a new row in the database. I noticed this effect while writing an app to parse an XML file and populate some tables. I noticed there were 1000+ inserts when I was only expecting around 50 or so - then I finally isolated this behavior.

How can I prevent these objects from being persisted implicitly?

Thanks,
-Charles

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

万劫不复 2024-07-17 13:15:57

将这种关系视为具有两个方面。 当您设置关系的一侧时,另一侧需要更新,因此在上面的情况下以及设置 ProductOptionCategory 时,它会有效地将新对象添加到层压 ProductOptionCategory 侧的 ProductOptions 关系中。

正如您已经发现的那样,解决方法是设置基础外键,以便 LINQ to SQL 不会以通常的方式跟踪对象,并且需要隐式指示它应该保留该对象。

当然,提高性能的最佳解决方案是从源数据中确定您不想添加哪些对象,并且从不首先创建实例。

Think of the relationship as having two sides. When you set one side of the relationship the other side needs to be updated so in the case above as well as setting the ProductOptionCategory it is effectively adding the new object to the ProductOptions relationship on the laminate ProductOptionCategory side.

The work-around is as you have already discovered and to set the underlying foreign key instead so LINQ to SQL will not track the objects in the usual way and require implicit indication it should persist the object.

Of course the best solution for performance would be to determine from the source data which objects you don't want to add and never create the instance in the first place.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文