我正在使用带有Cosmos集成的实体框架。我想从api更新实体。这是结构:
ApiController -> UnitOfWork -> Generic Repository
我的存储库定义如下:
public interface IRepository<TEntity> where TEntity : Entity
{
Task CreateAsync(TEntity entity);
Task<IEnumerable<TEntity>> ReadAsync(Expression<Func<TEntity, bool>> predicate);
Task<TEntity> UpdateAsync(TEntity entity);
Task DeleteAsync(TEntity entityId);
}
您可能已经发现,在存储库的实现中,我没有该实体的任何上下文。
更新方法如下:
public async Task<TEntity> UpdateAsync(TEntity entity)
{
_dbContext.Entry(entity).State = EntityState.Modified;
var updated = _dbContext.Set<TEntity>().Attach(entity);
return updated.Entity;
}
出于明显的原因,我不想从api中公开主键。从我的招摇定义中尝试PUT
方法会导致以下异常:
Unable to track an entity of type 'MyEntity' because alternate key property 'id' is null. If the alternate key is not used in a relationship, then consider using a unique index instead. Unique indexes may contain nulls, while alternate keys must not
就像错误消息提示一样,我在DbContext
中创建了一个唯一索引,如下所示:
modelBuilder.Entity<MyEntity>().HasIndex(p => p.MyProperty).IsUnique();
但是发生相同的异常。
如何在不了解实体具体实现细节的情况下很好地处理此问题?
编辑:
我也尝试过HasAlternateKey
,它绑定到通过api公开的属性,但是由于找不到实体而没有运气