One-To-Many Entity Framework 5 Update with code first

1.6k Views Asked by At

I have ONE entity that i want to update without updating its List of MANY entity. Im using Code-First But i cant get it to work... Im using Ninject and everything is working except my update...

//Entities

public class A
{
public int AId { get; set; }
public string Name { get; set; }
}


public class B
{
public int BId { get; set; }
public string Name { get; set; }
public virtual List<A>ListOfAs { get; set; }
}

//Interface

private EFDbContext context = new EFDbContext();

public IQueryable<B> Bs
        {
            get { return context.B; }
        }

        public void SaveBs(B b)
    {
        if (b.Id== 0)
        {
            context.B.Add(b);
            context.SaveChanges();
        }

        *//here i wanna call: 
        context.Entity(b).State = EntityState.Modified;
        BUT VS dont let me... I probably missing something out...*

        context.SaveChanges();

the Save method is working when i want to just add a new object to my database. But the update wont change anything...

I would appricate if anyone could tell me what im missing out...

/Thx J

2

There are 2 best solutions below

3
daryal On
if (b.Id== 0)
    {
        context.B.Add(b);
    }
else
   {
       context.B.Attach(b);
   }
   context.SaveChanges();
3
Md. Nazrul Islam On

Use The Following Criteria, This work for me

public BuyerInformation Update(BuyerInformation objBuyerInformation)
    {
        context.BuyerInformation.Attach(objBuyerInformation);
        context.Entry(objBuyerInformation).State = EntityState.Modified;
        context.SaveChanges();

        return objBuyerInformation;
    }