如何首次保存实体,需要将另一个预先存在的实体附加到实体上

时间:2022-08-08 02:21:28

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.

我需要将Company实体作为新实体保存到数据库中。为此,我需要将CompanyType实体与Company实体相关联。如果不这样做,我无法拯救公司。我是否将新创建的公司附加到上下文,然后将公司类型实体附加到公司,然后保存我的结果?这段代码有效......但感觉不对。

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?

CompanyType附加到另一个上下文并分离,这就是它在这里传递的原因。我是否应该更好地传递CompanyTypeID并查询同一个using语句中的关联对象?

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!

我无法忍受我必须采取这么多步骤来获得EF goign LINQ to SQL如此简单!仍然 - EF似乎比NHibernate更容易!

1 个解决方案

#1


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();

#1


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();