3

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: Debug values

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!

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

context.Funds.Include("Owner").FirstOrDefault(f => f.FundId == newTransaction.ToFund.FundId); worked. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.