本文介绍了实体框架更新说,当实体属性为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我想一个新的实体添加到现有的集合。但是当这样做的父实体抱怨其他的导航属性为null(虽然他们不是) 错误: When debugging the field Owner is loaded correctly:Fund class: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 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! 解决方案 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);You can find additional information about how EF loads related entities in this MSDN article 这篇关于实体框架更新说,当实体属性为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-30 03:12