Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

c# - 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...

i.e:

// 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 };
entities.Attach(dbAuthor);
entities.SaveChanges();

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 =)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

ctx.AttachToDefault(entity);

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

The second option allows you to write:

ctx.EntitySet.Attach(entity);

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

Alex


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...