0
我使用Web API創建了REST
服務,我使用EF Code First。 我的問題是,當我添加一個現有關係foreignId = 1
的實體時,EF給我添加了關係並將我的實體返回給foreignId = 2
。EF 6和Web API使用現有實體添加實體
POST object
{
"nom":"Test",
"actif":true,
"provinceId":1,
"province":{
"id": 1,
"nom": "Province ok",
"actif": true
}
}
Return object
{
"id": 1,
"nom": "Test",
"actif": true,
"provinceId": 2,
"province": {
"id": 2,
"nom": "Province ok"
},
}
我也會使用這種風格的存儲庫模式。
public abstract class ServiceCrud<TEntity> : ServiceBase
where TEntity : EntityBase
{
public virtual object Get()
{
// Context.
return Ctx.Set<TEntity>().OrderBy(x => x.Nom).ToList();
}
public virtual async Task<object> Get(int id)
{
// Context.
var entity = await Ctx.Set<TEntity>().FindAsync(id);
// Return.
return entity;
}
public virtual async Task<object> Add(TEntity entity)
{
// Check Validity.
CheckValidity(entity);
// Context.
Ctx.Set<TEntity>().Add(entity);
await Ctx.SaveChangesAsync();
// Return.
return entity;
}
public virtual async Task<object> Update(TEntity entity)
{
// Check Validity.
CheckValidity(entity);
// Context.
Ctx.Entry(entity).State = EntityState.Modified;
await Ctx.SaveChangesAsync();
// Return.
return entity;
}
public virtual void CheckValidity(TEntity entity)
{
// Nom unique.
var entityBase = Ctx.Set<TEntity>().AsNoTracking().FirstOrDefault(x => x.Nom == entity.Nom);
if (entityBase != null && (entity.Id == null || entity.Id != entityBase.Id))
throw new ValidationException("Le nom doit être unique");
}
}
謝謝你的幫忙。
Alex