实体框架:设置外键属性 [英] Entity Framework: Setting a Foreign Key Property

查看:200
本文介绍了实体框架:设置外键属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个表,看起来大致是这样的:

We have a table that looks roughly like this:

CREATE TABLE Lockers 
{
  UserID int NOT NULL PRIMARY KEY (foreign key),
  LockerStyleID int (foreign key),
  NameplateID int (foreign key)
}

所有按键的涉及到其他表,但由于方式的应用程序是分布式的,这是我们更容易的ID一起传递作为参数。因此,我们希望做到这一点:

All of the keys relate to other tables, but because of the way the application is distributed, it's easier for us to pass along IDs as parameters. So we'd like to do this:

Locker l = new Locker { 
  UserID = userID, 
  LockerStyleID = lockerStyleID, 
  NameplateID = nameplateID 
};
entities.AddLocker(l);

我们能做到这一点的LINQ到SQL,但不是EF?

We could do it in LINQ-to-SQL, but not EF?

推荐答案

此功能缺失似乎惹恼了很多人。

This missing feature seems to annoy a lot of people.


  • 好消息:MS将解决这一问题与.NET 4.0

  • 坏消息:现在,或者如果你被困在3.5你必须做的工作一点点,但它有可能

您必须这样做是这样的:

You have to do it like this:

Locker locker = new Locker();
locker.UserReference.EntityKey = new System.Data.EntityKey("entities.User", "ID", userID);
locker.LockerStyleReference.EntityKey = new EntityKey("entities.LockerStyle", "ID", lockerStyleID);
locker.NameplateReference.EntityKey = new EntityKey("entities.Nameplate", "ID", nameplateID);
entities.AddLocker(locker);
entities.SaveChanges();

这篇关于实体框架:设置外键属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆