假设两个表组和用户如下
[Groups] ([Id] [int] NOT NULL, [Name] [nchar](50) NULL);
[Users] ([Id] [int] NOT NULL, [Name] [nchar](50) NULL, [GroupId] [int] NOT NULL);
FOREIGN KEY([GroupId]) REFERENCES [Groups] ([Id])
其中GroupId是用户的外键。
然后我使用Linq-to-SQL类设计器来创建相关的类,并将以下类添加到项目中
public partial class Group
{
public override int GetHashCode()
{
return (Id.GetHashCode());
}
public override bool Equals(object item)
{
if ((item == null) || (item is System.DBNull))
return (false);
else
{
var temp = item as Group;
if (temp == null)
return (false);
else
if (_Id.Equals(0))
return (_Name.Equals(temp.Name));
else
return (_Id == temp.Id);
}
}
partial void OnValidate(System.Data.Linq.ChangeAction action)
{
var dc = new DB.DataContext();
if (action == System.Data.Linq.ChangeAction.Insert)
if (dc.Groups.Count(o => o.Name.Equals(_Name)) != 0)
throw new Exception("Name Already Exist On Insert");
if (action == System.Data.Linq.ChangeAction.Update)
if (dc.Groups.Count(o => (!o.Id.Equals(_Id) && o.Name.Equals(_Name))) != 0)
throw new Exception("Name Already Exist On Update");
}
}
public partial class User
{
public override int GetHashCode()
{
return (Id.GetHashCode());
}
public override bool Equals(object item)
{
if ((item == null) || (item is System.DBNull))
return (false);
else
{
var temp = item as User;
if (temp == null)
return (false);
else
if (_Id.Equals(0))
return (_Name.Equals(temp.Name));
else
return (_Id == temp.Id);
}
}
}
和
public static DB.Group f1()
{
DB.DataContext dc = new DB.DataContext();
if (dc.Groups.Count() == 0)
{
DB.Group group = new DB.Group() { Name = "admins" };
dc.Groups.InsertOnSubmit(group);
dc.SubmitChanges();
}
return dc.Groups.First();
}
public static void f2(DB.Group group, string name)
{
DB.DataContext dc = new DB.DataContext();
DB.User user = new DB.User() { Name = name, GroupId = group.Id, };
dc.Users.InsertOnSubmit(user);
dc.SubmitChanges();
}
public static void f3(DB.Group group, string name)
{
DB.DataContext dc = new DB.DataContext();
DB.User user = new DB.User() { Name = name, Group = group, };
dc.Users.InsertOnSubmit(user);
dc.SubmitChanges();
}
现在如果我打电话
DB.Group group = f1();
f2(group, "john");
f2(group, "bob");
然后一切顺利,但如果我打电话
DB.Group group = f1();
f2(group, "john");
f3(group, "bob");
它会抛出异常“插入时已存在名称”。实际上,已调用OnValidate并检测组表的重复名称。奇怪的行为是当要将新用户插入表中时调用OnValidate。这是怎么回事?我犯了错误吗?
答案 0 :(得分:0)
我猜是因为你在f3中创建了一个新的DataContext,它假设你想把group作为新记录插入。
您可以手动将组附加到新的DataContext,以便它不会尝试插入它。
public static void f3(DB.Group group, string name)
{
DB.DataContext dc = new DB.DataContext();
dc.Groups.Attach(group);
DB.User user = new DB.User() { Name = name, Group = group, };
dc.Users.InsertOnSubmit(user);
dc.SubmitChanges();
}
或者,您可以创建一个DataContext,而不是为每个方法创建一个新的。
答案 1 :(得分:0)
Group = group,
在f3中,您将组的实例附加到用户。然后你告诉datacontext插入用户。因为有组连接到用户,并且datacontext当前没有跟踪该组,所以它也假定该组也需要插入。