views:

101

answers:

1

I need to save a Company entity to the database as a new entity. In order to do this I need to associate a CompanyType entity to the Company entity. I can't save the Company without do this. Do I attach the newly created company to the context and then attach the company type entity to the company and then save my results? This code works...but just doesn't feel right.

public RepositoryStatus SaveCompany(Company company, CompanyType companyType)
    {
        RepositoryStatus rs = new RepositoryStatus();
        try
        {
            using (RanchBuddyEntities dc = new Connection().GetContext())
            {
                if (company.CompanyID > 0)
                {
                    company.UpdateDate = DateTime.Now;
                    Company original = dc.CompanySet.Where(c => c.CompanyID == company.CompanyID).FirstOrDefault();
                    dc.ApplyPropertyChanges("CompanySet", company);
                    dc.Attach(companyType);
                    company.CompanyTypesReference.Attach(companyType);
                }
                else
                {
                    company.CreateDate = DateTime.Now;
                    company.UpdateDate = DateTime.Now;
                    dc.AddToCompanySet(company);
                    dc.Attach(companyType);
                    company.CompanyTypesReference.Value = companyType;
                }
                dc.SaveChanges();
            }
            rs.SetObject(company);
            rs.StatusType = Status.StatusTypes.Success;
        }
        catch (Exception e)
        {
            rs.SetObject(company);
            rs.StatusType = Status.StatusTypes.Failure;
            rs.AddMessage(e.Message + Environment.NewLine + e.StackTrace);
        }

        return rs;
    }

The CompanyType was attached to another context and detached which is why it is passed in here. Would I be better off passing in the CompanyTypeID and query for the associated object inside of the same using statement?

I can't stand that I have to take so many steps to get EF goign where LINQ to SQL was so easy! Still - EF seems easier than NHibernate!

+1  A: 

I do it like this:

Company company = new Company();
company.CreateDate = DateTime.Now;
company.UpdateDate = DateTime.Now;
company.CompanyType = companyType;
RanchBuddyEntities.AddToCompanies(company);
RanchBuddyEntities.SaveChanges();
Mike Christiansen