我有两个类:LicenseType和EntityType。使用实体框架代码时首先处理相关数据
[Table("LicenseType")]
public class LicenseType : ComplianceBase, INotifyPropertyChanged
{
private List<Certification> _certifications = new List<Certification>();
private List<EntityType> _entityTypes = new List<EntityType>();
public List<EntityType> EntityTypes
{
get { return _entityTypes; }
set { _entityTypes = value; }
}
public List<Certification> Certifications
{
get { return _certifications; }
set { _certifications = value; }
}
}
和
[Table("EntityType")]
public class EntityType : ComplianceBase, INotifyPropertyChanged
{
private List<LicenseType> _licenseTypes = new List<LicenseType>();
public List<LicenseType> LicenseTypes
{
get { return _licenseTypes; }
set
{
_licenseTypes = value;
// OnPropertyChanged();
}
}
}
的从ComplianceBase两个派生,
public class ComplianceBase
{
private int _id;
private string _name;
private string _description;
public string Description
{
get { return _description; }
set
{
if (_description == value) return;
_description = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
public int Id
{
get { return _id; }
set
{
if (value == _id) return;
_id = value;
OnPropertyChanged();
}
}
public string Name
{
get { return _name; }
set
{
if (value == _name) return;
_name = value;
OnPropertyChanged();
}
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
我要的是能够做的是一个的EntityType与一个或多个LicenseTypes,关联起来,例如,一个EntityType“Primary Lender”可以与两个LicenseTypes,“贷款人许可证”和“抵押许可证”相关联。在这种情况下,我需要EntityType表中的一条记录,“Primary Lender”和我的LicenseType表中的两条记录:“贷方许可证”和“抵押许可证”。
添加相关LicenseTypes我的EntityType的代码是通过调用:
_currentEntity.LicenseTypes.Add(licenseType);
,然后调用_context.SaveChanges()
;
还有一个额外的表“EntityTypeLicenseTypes”用作关联这两个表的查找表。有两条记录可以将EntityType与两个相关的LicenseType一起加入。
这个工程。但是,我的代码还添加(它复制)LicenseType记录,并将其添加到正在关联的记录的LicenseType表中。
我该如何阻止这种情况发生?
当我运行代码,我得到一个错误:具有相同键的对象已经存在于ObjectStateManager。 ObjectStateManager不能使用同一个键跟踪多个对象。任何想法如何处理这个? – 2013-02-21 19:50:47
好吧 - 我解决了你的问题 - 问题是我使用了两个不同的DbContext实例 - 只要我“共享”它们,系统就能正常工作。谢谢! – 2013-02-21 20:10:06