简体   繁体   中英

Entity Framework says property is null when updating entity

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).

Error:

An exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in Ela.Facade.dll but was not handled in user code

Additional information: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

Fund State: Modified

Error: Field Owner is required

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

Sounds like you are missing the owner from the db context. You can't just new up the owner:

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

One other alternative is to Attach the entity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM