我在两个实体之间有一对一的关系,我想设置导航属性添加重复记录你我的表
因为我的英语很差,所以我在这里为你附上我的项目
tnx
我的代码在这里:
这是我的实体:
public partial class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Lastname { get; set; }
public int UserType { get; set; }
}
public partial class Storage : User
{
public virtual Store Store { get; set; }
}
public partial class Store
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Storage Storage { get; set; }
}
这是我的添加商店按钮:
User u = (User)(comboBox1.SelectedItem);
Storage st = new Storage(u);
Store s = new Store(textBoxStorename.Text);
s.SetStorage(st);
s.Save(st);
这里是我的商店类:
public partial class Store
{
public Store()
{
}
public Store(string name)
{
this.Name = name;
}
public void SetStorage(Storage s)
{
if (s != null)
{
this.Storage = s;
}
}
public void Save(Storage s)
{
using (var storekeeper = new TestContainer())
{
bool flag = false;
foreach (var item in storekeeper.Stores)
{
if (item.Equals(this))
{
flag = true;
}
}
if (flag)
{
MessageBox.Show("Duplicat Error", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
storekeeper.Users.Attach(s);
storekeeper.Stores.Add(this);
storekeeper.SaveChanges();
}
catch (Exception e )
{
MessageBox.Show(e.Message);
}
}
}
public override string ToString()
{
return this.Name;
}
}