我有两个课程:Transaction
和PosReference
。
transaction
可能与posReference
相关联posReference
必须有transaction
代码:
public class Transaction : Entity
{
[Key]
public Int64 Id { get; set; }
public virtual PosReference PosReference { get; set; }
}
public class PosReference : Entity
{
public Int64 Id { get; set; }
public virtual Transaction Transaction { get; set; }
public PosReference(Transaction transaction){
Id = transaction.Id;
}
}
和映射编写如下:
modelBuilder.Entity<Transaction>() // one-to-one or zero relation
.HasOptional(m => m.PosReference)
.WithRequired(t => t.Transaction);
如果我尝试一次添加一个transaction
和posReference
对,然后将上下文保存在数据库中,一切正常。
但是如果我尝试添加多个transaction-posReference
对,则抛出此异常:
违反了多重性约束。角色&#39; Transaction_PosReference_Target&#39;关系&#39; Data.Models.Transaction_PosReference&#39;具有多重性1或0..1。
是否可以添加多个(一对零/一对)?我应该如何更改我的模型或映射来实现这一目标?
编辑:
两项服务的简化代码如下:
public class TransactionServices {
private readonly IRepositoryAsync<Transaction> _repository;
public TransactionServices(IRepositoryAsync<Transaction> repository){
_repository = repository;
}
public Transaction Add(){
var transaction = new Transaction();
_repository.Insert(transaction);
return transaction;
}
}
public class PosReferenceServices {
private readonly IRepositoryAsync<PosReference> _repository;
public PosReferenceServices(IRepositoryAsync<PosReference> repository){
_repository = repository;
}
public PosReference Add(Transaction transaction){
var posReference = new PosReference(Transaction transaction){
Transaction = transaction
};
_repository.Insert(posReference);
return posReference;
}
}
在UnityConfig中配置存储库对象,如下所示:
.RegisterType<IRepositoryAsync<Transaction>, Repository<Transaction>>()
.RegisterType<IRepositoryAsync<PosReference>, Repository<PosReference>>()
以下是添加对象的功能:
public async Task<HttpResponseMessage> AddTransactions(List<PosTransaction> newTransactionList){
foreach (var posTransactionInfo in newTransactionList){
// I have omitted some unrelated parameters from PosReference to make code cleaner and to the point
var transaction = _transactionServices.Add();
var posReference = _posReferenceServices.Add(transaction);
// other posReference params would be set according to data in posTransactionInfo
}
await _unitOfWorkAsync.SaveChangesAsync();
return Request.CreateResponse(Message.PaywandOk());
}
编辑2:
两个实体上的Insert
函数执行以下操作:
private readonly IDataContextAsync _context;
private readonly DbSet<TEntity> _dbSet;
private readonly IUnitOfWorkAsync _unitOfWork;
public virtual void Insert(TEntity entity)
{
entity.ObjectState = ObjectState.Added;
_dbSet.Attach(entity);
_context.SyncObjectState(entity);
}