Reputation: 3654
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!
Upvotes: 3
Views: 422
Reputation: 2907
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
Upvotes: 2