【发布时间】:2013-11-11 21:06:21
【问题描述】:
我有 3 张桌子, 1. AttributeTypes(列:AttributeId (PK)、AttributeName、..) 2.位置(列:locationId(PK),LocationName,...) 3.LocationAttributeType(列:locationId(FK),AttributeId(FK))
每当我尝试从 GUI 插入新的位置记录及其属性类型时,它应该为 Table-Location 和 LocationAttributeType 创建新记录。但 EF 也尝试在 Table- AttributeTypes 中添加新记录,该记录仅用作参考表,不应在其中添加新记录/重复记录。我怎样才能防止这种情况发生?
这是我的代码,
GUI发送的模型是,
public class LocationDataModel
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Code { get; set; }
[DataMember]
public List<AttributeTypeDataModel> AssignedAttributes = new List<AttributeTypeDataModel>();
}
public class AttributeTypeDataModel
{
protected AttributeTypeDataModel() {}
public AttributeTypeDataModel(int id) { this.Id = id; }
public AttributeTypeDataModel(int id, string name)
: this(id)
{
this.Name = name;
}
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public virtual ICollection<LocationDataModel> Locations { get; set; }
}
EF 创建的实体是,
public partial class Location
{
public Location()
{
this.AttributeTypes = new List<AttributeType>();
}
public Location(int campusId, string code)
: this()
{
CampusId = campusId; Code = code;
}
public int Id { get; set; }
public int CampusId { get; set; }
public string Code { get; set; }
public virtual ICollection<AttributeType> AttributeTypes { get; set; }
}
public partial class AttributeType
{
public AttributeType()
{
this.Locations = new List<Location>();
}
public int AttributeTypeId { get; set; }
public string AttributeTypeName { get; set; }
public virtual ICollection<Location> Locations { get; set; }
}
我有以下代码将这些新位置添加到数据库,
private IEnumerable<TEntity> AddEntities<TModel, TEntity, TIdentityType>
(IEnumerable<TModel> models, Func<TModel, TIdentityType> primaryKey,
IGenericRepository<TEntity, TIdentityType> repository)
{
var results = new List<TEntity>();
foreach (var model in models)
{
var merged = _mapper.Map<TModel, TEntity>(model);
var entity = repository.Upsert(merged);
results.Add(entity);
}
repository.Save();
return results.AsEnumerable();
}
我正在使用以下通用存储库进行实体相关操作
public TEntity Upsert(TEntity entity)
{
if (Equals(PrimaryKey.Invoke(entity), default(TId)))
{
// New entity
return Context.Set<TEntity>().Add(entity);
}
else
{
// Existing entity
Context.Entry(entity).State = EntityState.Modified;
return entity;
}
}
public void Save()
{
Context.SaveChanges();
}
我在这里做错了什么?
【问题讨论】:
-
不想检查您的代码,因为它非常广泛,但您可能在某处遗漏了
Attach。 -
您能在我的代码中查看“Upsert”方法并建议我使用“附加”的正确位置吗?
标签: c# sql-server entity-framework ef-code-first