entity framework说更新实体时属性为null
我正在尝试将新实体添加到现有集合中。 但是当这样做时,“父”实体会抱怨其他导航属性为空(尽管它们不是)。
错误:
Ela.Facade.dll中出现“System.Data.Entity.Validation.DbEntityValidationException”类型的exception,但未在用户代码中处理
附加信息:一个或多个实体的validation失败。 有关详细信息,请参阅“EntityValidationErrors”属性。
基金国:修改
错误:需要字段所有者
调试字段时正确加载所有者:
基金类:
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 Transactions { get; set; } public Fund() { Transactions = new List(); } }
CreateTransaction方法:
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(); }
任何帮助或建议表示赞赏!
当您查找基金时,如果它们是虚拟的,它不会填充外键属性。 为了让他们被拉,你必须包括该财产; 这样做可以让您获得理想的结果。
var fund = context.Funds .Include(f => f.Owner) .FirstOrDefault(f => f.FundId == newTransaction.ToFund.FundId);
您可以在此MSDN文章中找到有关EF如何加载相关实体的其他信息
听起来你错过了db上下文中的所有者。 你不能只是新手所有者:
var fund = context.Funds.FirstOrDefault(f => f.FundId == newTransaction.ToFund.FundId); newTransaction.ToFund = fund; var owner = context.Owners.First(x => x.OwnerId == newTransaction.Owner.OwnerId); newTransaction.Owner = owner; fund.Transactions.Add(newTransaction);
另一种选择是Attach
实体。