Pavel Basha Pavel Basha - 1 year ago 50
C# Question

Update list in Entity Framework model

I have an Entity Framework model:

public class Application
{
[Key]
public int ApplicationID { get; set; }
public int PatentID { get; set; }

...

//------------------------------------
public string ApplicationNumber { get; set; }
public string Priority { get; set; }
public List<ApplicationPayment> Payments { get; set; }
= new List<ApplicationPayment>();
}


and payment's model:

public class ApplicationPayment
{
[Key]
public int PaymentID { get; set; }
public string PaymentName { get; set; }
public float Amount { get; set; }
public int PayNumber { get; set; }
public DateTime Date { get; set; } = new DateTime(2017, 12, 1);
public float TopicPart { get; set; }
}


Entity Framework creates additional foreign keys for me in
ApplicationPayment
model
Application_ApplicationID
.

I add a new instance in
ApplicationPayment
table that has number of the existing
Application
:sql models

But when I try to display this
ApplicationPayment
's table this returns the empty table.

I tried to add
ApplicationPayment
manually through SQL Server Management Studio and via fake-request. New line added but the list of ApplicationPayment is still empty.

Fake-request:

[HttpPut]
public void CreateApplicationPayment(int? id)
{
ApplicationPayment appPayment = new ApplicationPayment()
{
Amount = 80.0f,
Date = new DateTime(2017, 10, 25),
PaymentName = "payment",
PayNumber = 30,
TopicPart = 20
};

Application application = db.Applications.Find(id);

application.Payments.Add(appPayment);
db.SaveChanges();

}

Answer Source

Your collection property needs to be virtual if you want EF to automatically populate it:

public virtual List<ApplicationPayment> Payments { get; set; }

Also, if you're using EF 6 or previous, you'll need to make the type of that property ICollection<ApplicationPayment>, rather than List<ApplicationPayment>. I think EF Core relaxed this restriction, but I'm not sure. So, if you still have issues, change it there as well.

However, this is what's called lazy-loading, and it's not ideal in most scenarios. Additionally, if you're using EF Core, it still won't work, because currently EF Core does not support lazy loading. The better method is to eagerly load the relationship. This is done by using Include in your LINQ query:

Application application = db.Applications.Include(m => m.ApplicationPayments).SingleOrDefault(m => m.Id == id);

This will cause EF to do a join to bring in the related ApplicationPayments. You need to then use SingleOrDefault rather than Find, as Find doesn't work with Include. (Find looks up the object in the context first, before hitting the database, and as a result, cannot account for related items being available.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download