我正在尝试将新实体添加到现有集合中。但是,当这样做时,“父”实体抱怨其他导航属性为空(尽管它们不是)。
Error:
类型异常
发生“System.Data.Entity.Validation.DbEntityValidationException”
在 Ela.Facade.dll 中,但未在用户代码中处理
附加信息:一个或多个实体的验证失败。
有关更多详细信息,请参阅“EntityValidationErrors”属性。
基金状态:修改
错误:需要字段所有者
When debugging the field Owner is loaded correctly:
基金类别:
public class Fund
{
public int FundId { get; set; }
[Required]
[Index("IDX_FundName", 2, IsUnique = true)]
[MaxLength(25)]
public string Name { get; set; }
[Required]
[Index("IDX_FundIdentifier", 2, IsUnique = true)]
[MaxLength(25)]
public string Identifier { get; set; }
public double Balance { get; set; }
[Required]
[Index("IDX_FundName", 1, IsUnique = true)]
[Index("IDX_FundIdentifier", 1, IsUnique = true)]
public virtual ApplicationUser Owner { get; set; }
public virtual ICollection<Transaction> Transactions { get; set; }
public Fund()
{
Transactions = new List<Transaction>();
}
}
创建交易方法:
public Transaction CreateTransaction(Transaction newTransaction)
{
var context = new ApplicationDbContext();
try
{
var fund = context.Funds.FirstOrDefault(f => f.FundId == newTransaction.ToFund.FundId);
newTransaction.ToFund = fund;
fund.Transactions.Add(newTransaction);
context.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
return context.Transactions.FirstOrDefault();
}
任何帮助或建议表示赞赏!