伪造M:N与EntityKey的关联 [英] Faking M:N association with EntityKey

查看:85
本文介绍了伪造M:N与EntityKey的关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hï*

我在创建"假"时试图使用众所周知的技巧EntityReference上的EntityKey在保存实体之前不必获取相关实体(如果它不在上下文中)。这适用于1:N关联。但有人知道如何使用M:N的技巧吗?我现在正在快速浏览一下,看起来我无法让EF合作。 :)


Jiri {x2} Cincura

Hï *

I'm trying to use the well know trick when creating "fake" EntityKey on EntityReference before saving the entity to not have to fetch the related entity if it's not in context. This works fine for 1:N association. But does anybody know how to use the trick with M:N? I was doing some quick look right now and it looks I'm not able to convice EF to cooperate. :)


Jiri {x2} Cincura

推荐答案

在这种情况下,你必须处理物化对象(但你不要必须加载它们 - 你可以使用Attach())。假设您要在Product p1和Category c1之间添加关系(假设M:N关系):

In this case you have to deal with materialized objects (but you don't have to load them - you can use Attach()). Suppose you want to add a relationship between Product p1 and Category c1 (assuming M:N relationship):

var p1 = new Product() { ProductID = 123 };
var c1 = new Category() { CategoryID  = 456};

context.AttachTo("Products", p1);
context.AttachTo("Categories", c1);
p1.Categories.Add(c1);

context.SaveChanges();



这篇关于伪造M:N与EntityKey的关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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