How can I attach an Entity Framework object that isn't from the database?


I have a complete separation of my Entity Framework objects and my POCO objects, I just translate them back and forth...


// poco
public class Author
   public Guid Id { get; set; }
   public string UserName { get; set; }

and then I have an EF object "Authors" with the same properties..

So I have my business object

var author = new Author { UserName="foo", Id="Guid thats in the db" };

and I want to save this object so I do the following:

var dbAuthor = new dbAuthor { Id=author.Id, UserName=author.UserName };

but this gives me the following error:

An object with a null EntityKey value cannot be attached to an object context.

EDIT: It looks like I have to use entities.AttachTo("Authors", dbAuthor); to attach without an EntityKey, but then I have hard coded magic strings, which will break if I change my entity set names at all and I wont have any compile time checking... Is there a way I can attach that keeps compile time checking?

I would hope I'd be able to do this, as hard coded strings killing off compile time validation would suck =)

1/12/2013 9:11:36 AM

Accepted Answer

Have you tried using AttachTo and specifying the entity set?..

entities.AttachTo("Authors", dbAuthor);

where "Authors" would be your actual entity set name.

Yes there is a better way (well there should be). The designer should have generated "Add" methods to the ObjectContext for you which translate out to the call above.. So you should be able to do:


which should literally be:

public void AddToAuthors(Authors authors)
    base.AddObject("Authors", authors);

defined in the whateverobjectcontext.designer.cs file.

8/11/2012 12:27:27 PM

Just seeing this now. If you want to Attach() to the ObjectContext, i.e. convince the entity framework that an entity exists in the database already, and you want to avoid using magic strings i.e.

ctx.AttachTo("EntitySet", entity);

You can try two possibilities based on extension methods, both of which definitely make life more bearable.

The first option allows you to write:


and is covered in here: Tip 13 - How to attach an entity the easy way

The second option allows you to write:


and is covered here: Tip 16 - How to mimic .NET 4.0's ObjectSet today

As you can see both are really easy to use and avoid strings altogether.

Hope this helps


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow