Adding Entity object with foreign key
In database I have 2 tables:
Article: ID | Title| SectionID Section: ID | SectionName (all ids set as Identity Increment)I want to add new Article with specific SectionID (that exits in database).
I tired this:
Article art = new Article
{
Title = "title"
};
art.Section.SectionID = 0;
if (art.EntityState == EntityState.Detached)
{
Articlerctx.AddToArticles(art);
}
I get error on art.Section.SectionID = 0;
Object reference not set to an instance of an object
Do I need to create a complete objec开发者_运维知识库t just for one int field???
You can of course get the object from the database (I didn't see the "exists in database", sorry).
just grab the Section
object from your context and assign it.
art.Section = context.Section.FirstOrDefault(s => s.ID == 0);
In EF 4 you can check the box on the update model wizard to include foreign key fields in the model. If you do this, you can then change your code to:
Article art = new Article
{
Title = "title"
};
art.SectionID = 0;
if (art.EntityState == EntityState.Detached)
{
Articlerctx.AddToArticles(art);
}
art.SectionReference.EntityKey = new EntityKey("EntityModelName.EntitySetName", "IdFieldName", 0);
精彩评论