实体框架中的问题 [英] Attaching Issue in Entity Framework

查看:80
本文介绍了实体框架中的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个返回一个表(物理存储表)的存储过程。

I create a stored procedure which returns a table (physically stored table).

CREATE PROCEDURE uspTest
AS
BEGIN
 SELECT * from Table1
END

当我使用Entity Framework捕获输出时,会正确加载实体。

When I capture the output using Entity Framework, it loads up the entity properly.

var output = entities.Database.SqlQuery<Table1>("dbo.uspTest").ToList<Table1>();

输出变量包含从SP返回的数据,但它的Table1对象列表不不自动加载外键表。我添加了下面的代码来减轻这个问题。

the "output" variable contains the data returned from SP but it this List of Table1 object doesn't not load up foreign key tables automatically. I added below code to mitigate this problem

foreach (var member in output)
{
   entities.Table1s.Attach(member);
}

附加每个实体后,每个Table1成员都链接了所有子表。但是,当我第二次回到同样的方法时,它会给我一个错误的附件。

After attaching each entity all child tables are linked for each Table1 member. But, when I come back to this same method second time, it gives me an error failing to attach.

Attaching an entity of type 'Table1' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. 

我尝试将实体的状态设置为分离,但没有运气!有人有任何线索我应该在这里做什么?

i tried setting the state of entity to detached but of no luck!! Does anyone have any clue what i should do here?

我正在使用数据库第一种方法。

I'm using Database first approach.

推荐答案

的结果即使返回的对象的类型是实体类型,上下文也不会跟踪 Database.SqlQuery< TElement> 。如果您希望通过上下文跟踪返回的实体,那么您应该使用 DbSet< TEntity> .SqlQuery 方法:

var output = entities.Table1s.SqlQuery("dbo.uspTest").ToList();

这样你不需要使用额外的代码来附加实体。

This way you don't need to use extra code to attach the entities.

但是,当您已经有 DBSet 时,为什么要使用SP访问 Table1 表1> Table1s ?我想你有一个更复杂的存储过程,你这样做是为了解释你的问题,但如果这是你的SP,在@DLeh上面评论过,你应该使用 Linq to Entities

But, why do you want to access to the Table1 using a SP when you already have the DBSet<Table1> Table1s?. I guess you have a more complex stored procedure and you did this to explain your issue, but if that is your SP, as @DLeh commented above, you should use Linq to Entities.

这篇关于实体框架中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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