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 3393750
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T04:05:17+00:00 2026-05-18T04:05:17+00:00

I’m using the stub technique to update my POCO’s (used in a detached context,

  • 0

I’m using the “stub technique” to update my POCO’s (used in a detached context, ASP.NET MVC).

This is the code i currently have in my controller (which works):

[HttpPost]
public ActionResult Edit(Review review)
{
   Review originalReview = _userContentService.FindById(review.PostId) as Review;
   var ctx = _unitOfWork as MySqlServerObjectContext;
   ctx.ApplyCurrentValues("MyEntities.Posts", review);
   _unitOfWork.Commit();
   // ..snip - MVC stuff..
}

As you can see, there is code smell everywhere. 🙂

A few points:

  1. I use Dependency Injection (interface-based) for basically everything
  2. I use the Unit of Work pattern to abstract ObjectContext and provide persistence across multiple repositories
  3. Currently my IUnitOfWork interface has only 1 method: void Commit();
  4. Controller have IUserContentService and IUnitOfWork inject by DI
  5. IUserContentService calls Find in Repositories, which use the ObjectContext.

These are two things i don’t like with my above code:

  1. I don’t want to cast the IUnitOfWork as MySqlServerObjectContext.
  2. I don’t want the Controller to have to care about ApplyCurrentValues

I basically want my code to look like this:

[HttpPost]
public ActionResult Edit(Review review)
{
   _userContentService.Update(review);
   _unitOfWork.Commit();
   // ..snip - MVC stuff..
}

Any ideas how i can do that? (or something similar).

I already have smarts to work out the entity set name based on the type (combination of generics, pluralization), so don’t worry too much about that.

But i’m wondering where the best place to put ApplyCurrentValues is? It doesn’t seem appropriate to put it in the IUnitOfWork interface, as this is a persistence (EF) concern. For the same reason it doesn’t belong in the Service. If i put it in my MySqlServerObjectContext class (makes sense), where would i call this from, as nothing directly has access to this class – it is injected via DI when something requests IUnitOfWork.

Any thoughts?

EDIT

I have a solution below using the stub technique, but the problem is if i had retrieved the entity i am updating beforehand, it throws an exception, stating an entity with that key already exists.

Which makes sense, although i’m not sure how can resolve this?

Do i need to “check if the entity is already attached, if not, attach it?”

Can any EF4 experts out there help?

EDIT

Nevermind – found the solution, see answer below.

  • 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-18T04:05:18+00:00Added an answer on May 18, 2026 at 4:05 am

    Figured it out – wasn’t easy, so i’ll try to explain best i can. (for those who care)

    Controller Relevant Code:

    // _userContentService is IUserContentService
    _userContentService.Update(review);
    

    So, my controller calls a method called Update on IUserContentService, passing through the strongly-typed Review object.

    User Content Service Relevant Code

    public void Update(Post post)
    {
       // _userContentRepository is IPostRepository
       _userContentRepository.UpdateModel(post);
    }
    

    So, my service calls a method called UpdateModel on IPostRepository, passing through the strongly-typed Review object.

    Now, here is the tricky part.

    I actually have no specific Repositories. I have a generic repository called GenericRepository<T> : IRepository<T>, which handles all the different repositories.

    So when something requests a IPostRepository (which my service was doing), DI would give it a GenericRepository<Post>.

    But now, i give it a PostRepository:

    public class PostRepository : GenericRepository<Post>, IPostRepository
    {
       public void UpdateModel(Post post)
       {
          var originalPost = CurrentEntitySet.SingleOrDefault(p => p.PostId == post.PostId);
          Context.ApplyCurrentValues(GetEntityName<Post>(), post);
       }
    }
    

    And because the class derives from GenericRepository, it inherits all the core repository logic (Find, Add, etc).

    At first, i tried to put that UpdateModel code in the GenericRepository class itself (and then i wouldn’t have needed this specific repository), but the problem is the logic to retrieve the existing entity is based on a specific entity key, which the GenericRepository<T> would not know about.

    But the end result is the stitching is hidden deep down in the depths of the data layer, and i end up with a really clean Controller.

    EDIT

    This “stub technique” also works:

    public void UpdateModel(Post post)
    {
       var stub = new Review {PostId = post.PostId};
       CurrentEntitySet.Attach(stub);
       Context.ApplyCurrentValues(GetEntityName<Post>(), post);
    }
    

    But the problem is because Post is abstract, i cannot instantiate and therefore would have to check the type of Post and create stubs for every single derived type. Not really an option.

    EDIT 2 (LAST TIME)

    Okay, got the “stub technique” working with abstract classes, so now the concurrency issue is solved.

    I added a generic type parameter to my UpdateModel method, and the special new() constraint.

    Implementation:

    public void UpdateModel<T>(T post) where T : Post, new()
    {
       var stub = new T { PostId = post.PostId };
       CurrentEntitySet.Attach(stub);
       Context.ApplyCurrentValues(GetEntityName<Post>, post);
    }
    

    Interface:

    void UpdateModel<T>(T post) where T : Post, new();
    

    This prevents me from having to figure out the type of T manually, prevents concurrency issues and also prevents an extra trip to the DB.

    Pretty groovy.

    EDIT 3 (i thought the last time was the last time)

    The above “stub technique” works, but if i retrieve the object beforehand, it throws an exception stating an entity with that key already exists in the OSM.

    Can anyone advise how to handle this?

    EDIT 4 (OK – this is it!)

    I found the solution, thanks to this SO answer: Is is possible to check if an object is already attached to a data context in Entity Framework?

    I had tried to “check if the entity is attached” using the following code:

    ObjectStateEntry entry;
    CurrentContext.ObjectStateManager.TryGetObjectStateEntry(entity, out entry);
    

    But it always returned null, even through when i explored the OSM i could see my entity there with the same key.

    But this code works:

    CurrentContext.ObjectStateManager.TryGetObjectStateEntry(CurrentContext.CreateEntityKey(CurrentContext.GetEntityName<T>(), entity), out entry)
    

    Maybe because i’m using Pure POCO’s, the OSM had trouble figuring out the entity key, who knows.

    Oh and one other thing i added – so that i don’t have to add a specific repository for each entity, i created an attribute called “[EntityKey]” (public property attribute).

    All POCO’s must have 1 public property decorated with that attribute, or i throw an exception in my repository module.

    So my generic repository then looks for this property in order to create/setup the stub.

    Yes – it uses reflection, but it’s clever reflection (attribute-based) and i’m already using reflection for plularization of entity set names from T.

    Anyway, problem solved – all working fine now!

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

Sidebar

Related Questions

I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I want use html5's new tag to play a wav file (currently only supported
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti
Does anyone know how can I replace this 2 symbol below from the string
I'm making a simple page using Google Maps API 3. My first. One marker
We're building an app, our first using Rails 3, and we're having to build

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.