简体   繁体   中英

How do I add an object with the entity framework when it has a foreign key object that already exists

I have 2 tables:

tblAuthors
 - id
 - username

tblPosts
 - id
 - authorid

So if I create a new Post

var post = new Post { Id=Guid.NewId(), Author=new Author { UserName="username", Id="id in database } };

The author of the post is already in the database, but the post itself is not...

So I want to do:

entities.AddToPosts(obj);

but it tries to add the Author and the Post... is there a way to have it Save the author and add the post? Or just ignore the Author completely?

I have both the Post and the Author as my own POCO business objects, that were pulled from the database and then converted to my business layer. I don't want to have to re-pull them because I could have modified either in my business layer. So I just want to attach the objects.

I don't want to keep the data objects around, I pull them out and convert them to business objects and then don't touch them again until I want to push back to the database and I convert the business objects to data objects.

Shouldn't you first retrieve the Author record from the database to be able to set it in the Post object?

So you would you get:

var author = Author.Select(a => a.Id).FirstOrDefault();
var post = new Post { Id=Guid.NewId(), Author=author };
entities.AddToPosts(obj);

Maybe you could use the Attach and AttachTo ObjectContext to attach the object, but is not mentioned in the MSDN library whether a query to the database is executed. With some tracing you could check whether a database query occurs.

It is possible to mock a "well-known" entity, without hitting the database. Create a new entity object, set the properties of the entity that are used in the entity key, and call ObjectContext.AttachTo. This will add the entity to the context in the Unchanged state, and can now be referenced by other entities.

// AttachTo
var item = new Item() { ItemId = wellKnownId };
context.AttachTo( "Items", item );
Assert.AreEqual( EntityState.Unchanged, item.EntityState );

I have a hunch that functionality you are seeking for was announced for next version of EF. There was a whole topic related to entity associacions @ mix.

Or you can try to map AuthorId Column from db to entity as well. (it does not map by default) You can't map foreign keys, so you can't associate an object without getting one from db.

EDIT: and this is why I'm still using linq2sql which provides this functionality.

This functionality isn't completely supported in EF yet, I had to the following:

var post = new Post { Id=Guid.NewId(), AuthorReference.EntityKey = new EntityKey("Authors", "Id", authorIdValue) };
entities.AddToPost(post);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM