0

Hi I am using Entity Framework Code First, for my Database and CRUD operations, but when I am trying to add into couple of tables using entities.

Here is the message I am getting:

The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects duplicate objects

My create function is as below:

public T Create(T item)
{
    try
    {
        if (ufb != null && ufb.CurrentUser != null)
        {
            SetValue("CreatedByUserId", item, ufb.CurrentUser.Id);
            SetValue("UpdatedByUserId", item, ufb.CurrentUser.Id);
        }

        SetValue("DateCreated", item, DateTime.Now);
        SetValue("DateUpdated", item, DateTime.Now);

        var newEntry = this.DbSet.Add(item);
        this.Context.Database.Log = message => LogHandler.LogInfo(1111, message);
        try
        {
            this.Context.SaveChanges();
        }
        catch (Exception ex)
        {
            LogHandler.LogInfo(2501, ex.Message);
        }

        BuildMetaData(item, true, true);
        return newEntry;
    }
    catch (DbEntityValidationException dbEx)
    {
        // http://forums.asp.net/t/2014382.aspx?Validation+failed+for+one+or+more+entities+See+EntityValidationErrors+property+for+more+details+
        string msg = string.Empty;
        foreach (var validationErrors in dbEx.EntityValidationErrors)
        {
            foreach (var validationError in validationErrors.ValidationErrors)
            {
                msg += validationError.PropertyName;
                msg += "---";
                msg += validationError.ErrorMessage;
                msg += "||";
            }
        }
        throw new Exception("7777 CREATE EntityValidationErrors: " + msg);
    }
}

Here is how I am trying to call the create method for couple of Entities, can somebody please suggest me what am I doing wrong, any help please

public InspectionItem Create(InspectionItem inspectionItem)
{
    try
    {
        //------------------------------------------------------
        // save the indexes to the multiple categories,
        // then clear the list of category objects in the 
        //------------------------------------------------------
        List<int> inspectionCategoryIdlist = new List<int>();

        foreach (var itemCat in inspectionItem.InspectionItemCategory)
        {
            int itemCatId = itemCat.ViolationTypeId;
            inspectionCategoryIdlist.Add(itemCatId);
        }
        inspectionItem.InspectionItemCategory.Clear();

        inspectionItem.InspectionItemNumber = "TEMP"; // just get past the Create
        var saveInspectionItemCategories = inspectionItem.InspectionItemCategory;

        inspectionItem.InspectionItemNumber = CalculateInspectionItemNumber(inspectionItem.InspectionItemId);

      

        UnitOfWork.InspectionItemRepository.Create(inspectionItem);

        if ((inspectionItem != null) && (inspectionItem.InspectionItemId != null) && (inspectionItem.InspectionItemId > 0))
            foreach (var violationTypeId in inspectionCategoryIdlist)
            {
                var a = new InspectionItemViolationCategory();
                a.InspectionItem = inspectionItem;

                var violationType = new ViolationType();
                violationType = UnitOfWork.ViolationTypeRepository.Find(violationTypeId);
                a.ViolationType = violationType;

                UnitOfWork.InspectionItemViolationCategoryRepository.Create(a);
            }

        return inspectionItem;
    }
    catch (Exception ex)
    {
        LogHandler.LogError(2101, "Commit Fail in Inspection Item Create", ex);
        throw ex;
    }
}

Any suggestion or code sample anything helps, thanks a lot.

mohabbati
  • 1,162
  • 1
  • 13
  • 31
AbdulAleem
  • 63
  • 8
  • Does this answer your question? [The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects](https://stackoverflow.com/questions/15274539/the-relationship-between-the-two-objects-cannot-be-defined-because-they-are-atta) – mohabbati Aug 24 '21 at 15:59
  • No, its not helping me, because my parent object has not created any links for associate table like in that example – AbdulAleem Aug 24 '21 at 16:45

0 Answers0