假设两个表 Groups 和 Users 如下
[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。这是怎么回事?我犯错了吗?