Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6607241
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T19:28:56+00:00 2026-05-25T19:28:56+00:00

probably this question has been asked in many forms before but still I think

  • 0

probably this question has been asked in many forms before but still I think their is no clear solution with the scenario.

I have following entity classes.

public class Project
{
    public int ProjectId { get; set; }
    [Required(ErrorMessage="please enter name")]
    public string Name { get; set; }
    public string Url { get; set; }
    public DateTime CreatedOn { get; set; }
    public DateTime UpdatedOn { get; set; }
    public bool isFeatured { get; set; }
    public bool isDisabled { get; set; }
    public int GroupId { get; set; }
    public virtual Group Group { get; set; }
    [Required(ErrorMessage="Please select atleast one tag")]
    public virtual ICollection<Tag> Tags { get; set; }
}

public class Tag
{
    public int TagId { get; set; }
    public string Name { get; set; }
    public DateTime CreatedOn { get; set; }
    public DateTime UpdatedOn { get; set; }
    public virtual ICollection<Project> Projects { get; set; }
}

public class Group
{
    public int GroupId { get; set; }
    public string Name { get; set; }
    public DateTime CreatedOn { get; set; }
    public DateTime UpdatedOn { get; set; }
    public virtual ICollection<Project> Projects { get; set; }
}

I have viewmodel for project entity and a custom model binder for this viewmodel.

public class NewProjectModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        ProjectNewViewModel model = (ProjectNewViewModel)bindingContext.Model ??
            (ProjectNewViewModel)DependencyResolver.Current.GetService(typeof(ProjectNewViewModel));
        bool hasPrefix = bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName);
        string searchPrefix = (hasPrefix) ? bindingContext.ModelName + ".":"";

        //since viewmodel contains custom types like project make sure project is not null and to pass key arround for value providers
        //use Project.Name even if your makrup dont have Project prefix

        model.Project  = model.Project ?? new Project();
        //populate the fields of the model
        if (GetValue(bindingContext, searchPrefix, "Project.ProjectId") !=  null)
        {
            model.Project.ProjectId = int.Parse(GetValue(bindingContext, searchPrefix, "Project.ProjectId"));
        }

        //
        model.Project.Name = GetValue(bindingContext, searchPrefix, "Project.Name");
        model.Project.Url = GetValue(bindingContext, searchPrefix, "Project.Url");
        model.Project.CreatedOn  =  DateTime.Now;
        model.Project.UpdatedOn = DateTime.Now;
        model.Project.isDisabled = GetCheckedValue(bindingContext, searchPrefix, "Project.isDisabled");
        model.Project.isFeatured = GetCheckedValue(bindingContext, searchPrefix, "Project.isFeatured");
        model.Project.GroupId = int.Parse(GetValue(bindingContext, searchPrefix, "Project.GroupId"));
        model.Project.Tags = new List<Tag>();

        foreach (var tagid in GetValue(bindingContext, searchPrefix, "Project.Tags").Split(','))
        {
            var tag = new Tag { TagId = int.Parse(tagid)};
            model.Project.Tags.Add(tag);
        }

        var total = model.Project.Tags.Count;

        return model;
    }

    private string GetValue(ModelBindingContext context, string prefix, string key)
    {
        ValueProviderResult vpr = context.ValueProvider.GetValue(prefix + key);
        return vpr == null ? null : vpr.AttemptedValue;
    }

    private bool GetCheckedValue(ModelBindingContext context, string prefix, string key)
    {
        bool result = false;
        ValueProviderResult vpr = context.ValueProvider.GetValue(prefix + key);
        if (vpr != null)
        {
            result = (bool)vpr.ConvertTo(typeof(bool));
        }

        return result;
    }
}

//My project controller edit action defined as under:
[HttpPost]
[ActionName("Edit")]
public ActionResult EditProject( ProjectNewViewModel ProjectVM)
{
   if (ModelState.IsValid) {
       projectRepository.InsertOrUpdate(ProjectVM.Project);
       projectRepository.Save();
       return RedirectToAction("Index");
   } 
   else {
    ViewBag.PossibleGroups = groupRepository.All;
        return View();
   }
}


//Group Repository
public void InsertOrUpdate(Project project)
    {
        if (project.ProjectId == default(int)) {
            // New entity
            foreach (var tag in project.Tags)
            {
                context.Entry(tag).State = EntityState.Unchanged;
            }
            context.Projects.Add(project);
        } else {               
            context.Entry(project).State = EntityState.Modified;
        }
    }

Now when I have a project inside edit view and i choose new tags for the project and submits the form edit action parameter use model binder and set all the properties of project object including tags. But when the project object is passed to insertorupdate method of grouprepository all the changes that we made get sotred in database except Tags collection property now I am really frustrated with this thing.

Please provide me the solution that would not make changes in the structure have been developed this far.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T19:28:57+00:00Added an answer on May 25, 2026 at 7:28 pm

    Something like this for your else case in InsertOrUpdate (the if case is fine in my opinion) might work:

    //...
    else {
        // Reload project with all tags from DB
        var projectInDb = context.Projects.Include(p => p.Tags)
            .Single(p => p.ProjectId == project.ProjectId);
    
        // Update scalar properties of the project
        context.Entry(projectInDb).CurrentValues.SetValues(project);
    
        // Check if tags have been removed, if yes: remove from loaded project tags
        foreach(var tagInDb in projectInDb.Tags.ToList())
        {
            // Check if project.Tags collection contains a tag with TagId
            // equal to tagInDb.TagId. "Any" just asks: Is there an element
            // which meets the condition, yes or no? It's like "Exists".
            if (!project.Tags.Any(t => t.TagId == tagInDb.TagId))
                projectInDb.Tags.Remove(tagInDb);
        }
    
        // Check if tags have been added, if yes: add to loaded project tags
        foreach(var tag in project.Tags)
        {
            // Check if projectInDb.Tags collection contains a tag with TagId
            // equal to tag.TagId. See comment above.
            if (!projectInDb.Tags.Any(t => t.TagId == tag.TagId))
            {
                // We MUST attach because tag already exists in the DB
                // but it was not assigned to the project yet. Attach tells
                // EF: "I know that it exists, don't insert a new one!!!"
                context.Tags.Attach(tag);
                // Now, we just add a new relationship between projectInDb and tag,
                // not a new tag itself
                projectInDb.Tags.Add(tag);
            }
        }
    }
    
    // context.SaveChanges() somewhere later
    

    SaveChanges will actually save the formerly reloaded project with the tag list due to EF change detection. The project passed into the method is even not attached to the context and just used to update the reloaded project and its tag list.

    Edit

    context.Tags.Attach(tag); added to code, otherwise SaveChanges would create new tags in the database.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

This is probably a question that has been asked before, but I couldn't find
You're probably thinking this has been asked a million times before but I think
I know this question has probably been asked so many times here, but I
Sorry I know this question has probably been asked before, but do you know
This has probably been asked before on SO, but I was unable to find
I know this question has probably been asked already but I would really like
This has probably been asked before, but a quick search only brought up the
This question has been asked before ( link ) but I have slightly different
I realise that this question has probably been asked to death, but none of
This probably has been asked before but all I can find are questions regarding

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.