我在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();
}
}