实体框架说更新实体时属性为null

时间:2015-08-18 14:33:46

标签: c# entity-framework

我试图将新实体添加到现有集合中。但是,当这样做时,父母会这样做。实体抱怨其他导航属性为空(尽管它们不是)。

错误:

  

类型的例外   ' System.Data.Entity.Validation.DbEntityValidationException'发生了   在Ela.Facade.dll中但未在用户代码中处理

     

其他信息:一个或多个实体的验证失败。   请参阅' EntityValidationErrors'物业详情。

     

基金州:已修改

     

错误:需要字段所有者

调试字段时正确加载所有者: Debug values

基金类:

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方法:

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();
}

感谢任何帮助或建议!

2 个答案:

答案 0 :(得分:2)

当您查找基金时,如果它们是虚拟的,它不会填充外键属性。为了让他们被拉,你必须包括该财产;这样做可以让你获得理想的结果。

Array
(
    [0] => Wildebeest
    [1] => Greater Kudu
    [2] => Blue And Yellow Macaw
)

您可以在此MSDN article

中找到有关EF如何加载相关实体的其他信息

答案 1 :(得分:0)

听起来你错过了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实体。