EF4 One To Many Relationsihp,How do i refresh an object which has childs?
i made a code first model which has these POCO:
public class Customer
{
public int CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int gender { get; set; }
public virtual List<Order> Orders { get; set; }
}
public class Order
{
public int OrderId { get; set; }
public string OrderName { get; set; }
}
context:
public class DatabaseContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>().HasKey(x => x.OrderId);
modelBuilder.Entity<Customer>().HasKey(z => z.CustomerId);
base.OnModelCreating(modelBuilder);
}
public DbSet<Order> Orders { get; set; }
public DbSet<Customer> Customers { get; set; }
}
now everything is fine:
but when i run this code:
private void button2_Click(object sender, EventArgs e)
{
DatabaseContext db = new DatabaseContext();
if (cs == null)
cs = db.Customers.FirstOrDefault();
db.Orders.Remove(db.Orders.FirstOrDefault());
db.SaveChanges();
MessageBox.Show(cs.Orders.Count.ToString());
}
count of cs.Orders.Count
always stays the same.
what im doing wrong ?
note: all orders belo开发者_Go百科ng to the same customer im just making a reproduce of a more complicated situation.
the question in another words how do i refresh the state of cs with all its childs ?
thanks in advance..
Did you mean for this line:
db.Orders.Remove(db.Orders.FirstOrDefault());
To actually read like this:
db.Orders.Remove(cs.Orders.FirstOrDefault());
Don't you want to remove the order from the customer?
With this line:
cs = db.Customers.FirstOrDefault();
You are getting the first customer in the table and assigning it to cs.
With this line:
db.Orders.Remove(db.Orders.FirstOrDefault());
You are removing the first order in the order table, which may or may not be an order related to the Customer cs.
Would you not want to do something like:
db.Orders.Remove(db.Orders.Where(o => o.CustomerId == cs.CustomerId).FirstOrDefault());
obviously i am just guessing the key names
精彩评论