user5980267
user5980267

Reputation:

EntityState Modified SaveChanges dont save

public static Result SaveCutomer(Customer customer)
{
    using (AshdorEntities context = new AshdorEntities())
    {
        try
        {
            Contact con = null;
            if (customer.customerId == 0)//new customer
            {
                customer.enterDate = DateTime.Now;
                customer.Contact.dateEnter = customer.enterDate;
                con = context.Contact.Add(customer.Contact);
                customer.Contact = con;
                customer.customerId = con.contactId;

            }
            else
                context.Customer.Attach(customer);

            context.Entry(customer).State = con != null ?
                         EntityState.Added :
                         EntityState.Modified;
            context.SaveChanges();
        }
        catch 
        {
            return new Result() { status = false, massege = MassegesResult.ADDING_FAILED };
        }

        return new Result() { status = true, massege = MassegesResult.ADDING_SUCCESSFUL };
    }
}

Upvotes: 3

Views: 113

Answers (1)

Seabizkit
Seabizkit

Reputation: 2415

This is not a working solution... rather trying to help by pointing out bits which dont flow nicely....

public static Result SaveCutomer(Customer customer)
{
    using (AshdorEntities context = new AshdorEntities())
    {
        try
        {
            //assumption is that its always a disconnected entity if not you will need to check
            context.Customer.Attach(customer);

            //this seems wrong as well
            Contact con = null;

            customer.enterDate = DateTime.Now;

            //this seems wrong as well
            customer.Contact.dateEnter = customer.enterDate;

            //this seems wrong as well
            con = context.Contact.Add(customer.Contact);

            customer.Contact = null;
            //this seems wrong as well
            customer.customerId = con.contactId;

            if (customer.customerId == 0)//new customer
            {
                context.Entry(customer).State = EntityState.Added 
            }
            else //existing 
            {
                context.Entry(customer).State = EntityState.Modified; 
            }
            context.SaveChanges();
        }
        catch 
        {
            return new Result() { status = false, massege = MassegesResult.ADDING_FAILED };
        }

        return new Result() { status = true, massege = MassegesResult.ADDING_SUCCESSFUL };
    }
}

Upvotes: 1

Related Questions