我在 VS2010 中创建了一个 EDM 模型。Permissions
并且Roles
是我模型中的实体,具有多对多关系。我正在尝试在每个集合中的两个条目之间添加关系。
此代码有效:
private static void AttemptToLink() {
using (var context = new UserAuthEntities()) {
p = context.Permissions.Include("Roles").First();
r = context.Roles.First();
p.Roles.Add(r);
context.SaveChanges();
}
}
但是下面的代码没有。有人可以告诉我我做错了什么吗?
internal class Program {
private static Permission p;
private static Role r;
private static void Main(string[] args) {
LoadEntities();
LinkEntities();
SaveEntities();
Pause();
}
private static void LoadEntities() {
using (var context = new UserAuthEntities()) {
p = context.Permissions.Include("Roles").First();
r = context.Roles.Include("Permissions").First();
}
}
private static void LinkEntities() {
p.Roles.Add(r);
}
private static void SaveEntities() {
using (var context = new UserAuthEntities()) {
context.Attach(p);
context.Attach(r);
int count = context.SaveChanges();
Console.WriteLine(String.Format("Saved {0}.", count));
}
}
private static void Pause() {
Console.Write("Press enter...");
Console.Read();
}
}