我有一个实体,它拥有另一个实体的虚拟集合。当我尝试通过填充新插入的对象的虚拟集合来插入数据时,它会抛出具有相同键的对象已经存在的错误。
我知道当未创建实体时,它将具有0值的标识字段。但是当我将数据存储在主表中时,我需要存储数据集合。
public virtual void Insert(TEntity entity)
{
((IObjectState)entity).ObjectState = ObjectState.Added;
entityDbSet.Attach(entity);
dataContext.SyncObjectState(entity);
}
这是我正在使用的插入方法。以下是此操作的poco类(用于扩展类以保存数据集合的部分实现)。
public partial class UserDefinedData
{
public int ID { get { return this.UserSelectedDValueID; } set { this.UserSelectedDValueID = value; } }
public string Name { get { return this.entityTypeName; } }
public virtual AM_AssetLocations AM_AssetLocations { get; set; }
}
public partial class AM_AssetLocations
{
// Reverse navigation
public virtual ICollection<UserDefinedData> UserDefinedDatas { get; set; }
}
我使用json传递数据。这似乎也是正确的。因为虚拟的数据集合正确地添加到实体中。
{"entity":{"ID":"0","CreatedByID":"0","CreatedDate":"04-13-2014 10:48","ModifiedByID":"","ModifiedDate":"","DeletedByID":"","DeletedDate":"","Deleted":"false","Name":"h","Active":"true","DisplayOrder":"0","Test Decimal":"10","":"","Test Number":"10","Test Plain Text":"h","Test RTF":"<p>hsj</p>","Test Yes No":"false","Test Yes No 2":"true","TestDate":"01-Apr-2014","TestDateTime":"10:00 AM","UserDefinedDatas":[{"EntityType":"AM_AssetLocations","EntityTypeID":"0","CreatedByID":"0","UserDefinedFieldID":"123","ValueNumber":"10"},{"EntityType":"AM_AssetLocations","EntityTypeID":"0","CreatedByID":"0","UserDefinedFieldID":"124","ValueListItemID":"25"},{"EntityType":"AM_AssetLocations","EntityTypeID":"0","CreatedByID":"0","UserDefinedFieldID":"122","ValueNumber":"10"},{"EntityType":"AM_AssetLocations","EntityTypeID":"0","CreatedByID":"0","UserDefinedFieldID":"117","ValueString":"h"},{"EntityType":"AM_AssetLocations","EntityTypeID":"0","CreatedByID":"0","UserDefinedFieldID":"119","ValueString":"<p>hsj</p>"},{"EntityType":"AM_AssetLocations","EntityTypeID":"0","CreatedByID":"0","UserDefinedFieldID":"125","ValueYesNo":0},{"EntityType":"AM_AssetLocations","EntityTypeID":"0","CreatedByID":"0","UserDefinedFieldID":"126","ValueYesNo":1},{"EntityType":"AM_AssetLocations","EntityTypeID":"0","CreatedByID":"0","UserDefinedFieldID":"120","ValueDate":"01-Apr-2014"},{"EntityType":"AM_AssetLocations","EntityTypeID":"0","CreatedByID":"0","UserDefinedFieldID":"121","ValueDate":"08-Apr-2014 10:00 AM"}]}}
请帮我解决这个问题。
注意:只是为了解决这个相同的密钥异常,如果我尝试分配我自己的身份字段,它会抛出参照完整性异常。我知道存储realative集合应该可以正常工作。但它不适合我。请给我一些指导和解决方案。
谢谢, 萨钦
答案 0 :(得分:1)
Attach
用于附加现有实体。
上下文应该自己分配适当的状态,在你的情况下不需要手动执行
public virtual void Insert(TEntity entity)
{
//((IObjectState)entity).ObjectState = ObjectState.Added;
context.TEntityDbSet.Add(entity);//Add, not Attach!
//dataContext.SyncObjectState(entity);
context.SaveChanges()
}
答案 1 :(得分:0)
嗨谢谢大家的帮助。我改变了执行此操作的方式。我创建了存储过程,它接受主要实体和用户定义的子集合表类型,可以从.net页面作为数据集传递。这对我来说很好。
感谢。