实体框架表示更新实体时属性为空
我正在尝试向现有集合添加一个新实体。但是,当这样做时,父实体会抱怨其他导航属性为空(尽管不是)。
I'm trying to add a new entity to an existing collection. But when doing so the 'parent' entity complains the other navigational properties are null (although they aren't).
错误:
类型为
'System.Data.Entity.Validation.DbEntityValidationException'的异常在Ela.Facade.dll中发生
,但未在用户代码中处理
An exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in Ela.Facade.dll but was not handled in user code
附加信息:一个或多个实体的验证失败。
有关详情,请参阅EntityValidationErrors属性。
Additional information: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
基金状态:修改
错误:需要字段所有者
调试字段时所有者已正确加载:
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>();
}
}
CreateTransaction方法:
CreateTransaction method:
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();
}
任何帮助或建议不胜感激!
Any help or recommendations are appreciated!
当您查找资金时,如果它们是虚拟的,它不会填充外键属性。 200新X-45旗新新新新旗新新旗新新旗新新旗新新旗新新旗新新旗新新旗新新旗新新旗新新200新新旗新新旗新新旗旗哨旗新新新这样做可以让您获得所需的结果。
When you look up the fund, it does not populate the foreign key properties if they are virtual. In order to have them pulled you have to include that property; doing so will allow you to get the desired results.
var fund =
context.Funds
.Include(f => f.Owner)
.FirstOrDefault(f => f.FundId == newTransaction.ToFund.FundId);
您可以在这个 MSDN文章