What is the best way to connect an Entity Framework object that isn't a database object?

.net-3.5 c# entity-framework linq-to-entities

Question

My Entity Framework objects and POCO objects are completely separate from one another; I just translate them back and forth.

i.e:

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

I also have an EF object called "Authors" with the same characteristics.

I now have my work-related item.

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

and I do the following because I want to store this object:

var dbAuthor = new dbAuthor { Id=author.Id, UserName=author.UserName };
entities.Attach(dbAuthor);
entities.SaveChanges();

nonetheless, I get the following error:

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

EDIT: It seems that I must utilize entities. I could connect without using an EntityKey by using AttachTo("Authors", dbAuthor); but then I'd have hard-coded magic strings that would fail if I changed the names of my entity sets in any way, and I wouldn't have any compile-time verification. Is there a way I can connect anything that keeps track of the build time?

I would want to be able to accomplish this since it would be bad if hard-coded strings eliminated compile-time validation.

1
22
1/12/2013 9:11:36 AM

Accepted Answer

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

entities.AttachTo("Authors", dbAuthor);

where "Authors" would be the name of your real entity set.

Edit:
There is a better method, it's true (well there should be). The call above should have been translated out for you by the designer as "Add" techniques to the ObjectContext. Thus, you ought to be able to:

entities.AddToAuthors(dbAuthor);

it should really read:

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

the whateverobjectcontext.designer.cs file defines.

13
8/11/2012 12:27:27 PM

Popular Answer

I just noticed this. If you want to avoid utilizing magic strings, that is, if you want to attach() to the object context rather than convincing the entity framework that an entity already exists in the database

ctx.AttachTo("EntitySet", entity);

You may attempt two extension method-based options, both of which unquestionably make life more comfortable.

The first option enables you to type:

ctx.AttachToDefault(entity);

and is discussed here: zzz 21 zzz

The second choice enables you to type:

ctx.EntitySet.Attach(entity);

, which is addressed here: Tip 16: How to imitate the ObjectSet in.NET 4.0 today

As you can see, both are really simple to use and completely free of strings.

Hope this is useful.

Alex



Related Questions





Related

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