开发者

Linq to enties, insert foreign keys

I am using the ADO entity framework for the first time and am not sure of the best way of inserting db recored that contain foreign keys.

this is the code that i am using, I would appreciate any comments and suggestion on this.

using (KnowledgeShareEntities entities = new KnowledgeShareEntities())
            {
                Questions question = new Questions();
   开发者_开发问答             question.que_title = questionTitle;
                question.que_question_text = questionText;
                question.que_number_of_views = 0;
                question.que_is_anonymous = isAnonymous;
                question.que_last_activity_datetime = DateTime.Now;
                question.que_timestamp = DateTime.Now;
                question.CategoriesReference.Value = Categories.CreateCategories(categoryId);
                question.UsersReference.Value =  Users.CreateUsers(userId);
                entities.AddToQuestions(question);
                entities.SaveChanges();

                return question.que_id;
            }  


You should use something like

question.UsersReference.EntityKey =  new EntityKey("MyEntities.Users",
    "ID", userId);

You don't have to have User object to set up foreign key, just use ID.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜