简体   繁体   English

使用外键添加实体对象

[英]Adding Entity object with foreign key

In database I have 2 tables: 在数据库中,我有2个表:
Article: ID | 文章:ID | Title| 标题| SectionID SectionID
Section: ID | 栏目:ID | SectionName 段名
(all ids set as Identity Increment) (所有ID均设置为“身份增量”)

I want to add new Article with specific SectionID (that exits in database). 我想添加具有特定SectionID的新Article(在数据库中退出)。

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; 我在art.Section.SectionID = 0上收到错误;

Object reference not set to an instance of an object 你调用的对象是空的

Do I need to create a complete object just for one int field??? 我是否需要为一个int字段创建一个完整的对象???

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. 只需从上下文中获取Section对象并进行分配即可。

art.Section = context.Section.FirstOrDefault(s => s.ID == 0);
art.SectionReference.EntityKey = new EntityKey("EntityModelName.EntitySetName", "IdFieldName", 0);

In EF 4 you can check the box on the update model wizard to include foreign key fields in the model. 在EF 4中,您可以选中更新模型向导上的框,以在模型中包括外键字段。 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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