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

  • Home
  • SEARCH
  • 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 388437
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 12, 20262026-05-12T15:46:10+00:00 2026-05-12T15:46:10+00:00

I’ve finally gotten this working after days of struggle. I’ve got a simple database

  • 0

I’ve finally gotten this working after days of struggle.

I’ve got a simple database of People and Departments:

ADO.NET Entity Framework Entity Data Model diagram with Department and Person objects http://img39.imageshack.us/img39/1368/edmxdepartmentperson.gif

I can use strongly-typed ASP.NET MVC views for reference/navigation properties! See the list of departments…

ASP.NET MVC with DropDownList http://img11.imageshack.us/img11/7619/dropdownlistdepartment.gif

Part of my Person/Edit view:

<% using (Html.BeginForm()) {%>
    <%= Html.Hidden("Id", Model.Id) %>
    <fieldset>
        <legend>Fields</legend>
        <p>
            <label for="Name">Name:</label>
            <%= Html.TextBox("Name", Model.Name) %>
        </p>
        <p>
            <label for="DepartmentId">Department:</label>
            <%= Html.DropDownList("DepartmentId", new SelectList((IEnumerable)ViewData["Departments"], "Id", "Name"))%>
        </p>
        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
<% } %>

Part of my Person controller:

//
// GET: /Person/Edit/5

public ActionResult Edit(Guid id)
{
    ViewData["Departments"] = ctx.Department;
    Person model = (from Person p in ctx.Person
                    where p.Id == id
                    select p).FirstOrDefault();
    return View(model);
}

//
// POST: /Person/Edit

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Person model)
{
    ctx.AttachUpdated(model);  //extension
    ctx.SaveChanges();
    return RedirectToAction("Index");
}

To get this working, I extended the Person EntityObject with a new DepartmentId property.

using System;
using System.Data;
using System.Data.Objects.DataClasses;

namespace ProjectName.Models
{
    public partial class Person : EntityObject
    {
        public Guid DepartmentId
        {
            get
            {
                try
                {
                    return (Guid)this.DepartmentReference.EntityKey.EntityKeyValues[0].Value;
                }
                catch
                {
                    return Guid.Empty;
                }
            }
            set
            {
                this.DepartmentReference.EntityKey = new EntityKey("JunkEntities.Department", "Id", value);
            }
        }
    }
}

And I extended the Entity Framework ObjectContext with new AttachUpdated and ApplyReferencePropertyChanges methods:

using System;
using System.Data;
using System.Data.Objects;
using System.Data.Objects.DataClasses;

public static class EntityFrameworkExtensionMethods
{

    public static void AttachUpdated(this ObjectContext ctx, EntityObject objectDetached)
    {
        if (objectDetached.EntityKey == null)
        {
            String entitySetName = ctx.DefaultContainerName + "." + objectDetached.GetType().Name;
            Guid objectId = (Guid)objectDetached.GetType().GetProperty("Id").GetValue(objectDetached, null);
            objectDetached.EntityKey = new System.Data.EntityKey(entitySetName, "Id", objectId);
        }
        if (objectDetached.EntityState == EntityState.Detached)
        {
            object currentEntityInDb = null;
            if (ctx.TryGetObjectByKey(objectDetached.EntityKey, out currentEntityInDb))
            {
                ctx.ApplyPropertyChanges(objectDetached.EntityKey.EntitySetName, objectDetached);
                ctx.ApplyReferencePropertyChanges((IEntityWithRelationships)objectDetached,
                                                  (IEntityWithRelationships)currentEntityInDb);  //extension
            }
            else
            {
                throw new ObjectNotFoundException();
            }
        }
    }

    public static void ApplyReferencePropertyChanges(this ObjectContext ctx, IEntityWithRelationships newEntity, IEntityWithRelationships oldEntity)
    {
        foreach (var relatedEnd in oldEntity.RelationshipManager.GetAllRelatedEnds())
        {
            var oldRef = relatedEnd as EntityReference;
            if (oldRef != null)
            {
                var newRef = newEntity.RelationshipManager.GetRelatedEnd(oldRef.RelationshipName, oldRef.TargetRoleName) as EntityReference;
                oldRef.EntityKey = newRef.EntityKey;
            }
        }
    }

}

I just wanted to document my progress here. Please suggest improvements.


Thanks:

  • Alex James
  • Cesar de la Torre
  • Griff Townsend
  • Steve Willcock
  • jrista
  • Tomas Lycken
  • Thomas Levesque
  • Danny Simmons
  • Stefan Cruysberghs
  • 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-12T15:46:10+00:00Added an answer on May 12, 2026 at 3:46 pm

    I’ve begun working with ASP.NET MVC which is why I came upon this thread, so I’m not sure if you you’re still checking for improvements.

    I don’t like the idea of adding the new property to a partial class on the entity framework because it doesn’t allow for as much change.
    Try labeling your Deparment DropDown “Department.Id” like this

    <p>
        <label for="Department.Id">Department:</label>
    <%= Html.DropDownList("Department.Id", new SelectList((IEnumerable)ViewData["Departments"], "Id", "Name"))%>
    </p>
    

    The ModelBinding of the MVC Framework will pick up the value and apply it to the “Id” Property of the “Department” Navigation Property. What I found is that the other values of Department are null, but that is not significant. Now you have a way of retrieving the correct Department Entity and applying it to the Department Navigation Property of the new Person Entity created in the Model Bind to your Action parameter, something like:

    newPerson.Department = ctx.Department.First(d => d.DepartmentId == newPerson.Department.Id);
    

    In doing it this way, you don’t need to update your Entity at all for a property it should have.

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

Sidebar

Related Questions

For some reason, after submitting a string like this Jack’s Spindle from a text
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
Let's say I'm outputting a post title and in our database, it's Hello Y&#8217;all
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
this is what i have right now Drawing an RSS feed into the php,
I've got a string that has curly quotes in it. I'd like to replace
I have this code to decode numeric html entities to the UTF8 equivalent character.
I am doing a simple coin flipping experiment for class that involves flipping a

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.