Linq2SQL 数据库设计:映射复合/代理键
想象一下我有一个巨大的数据库,它存储来自不同数据源(例如两个不同论坛)的线程和帖子。对于每个数据源,实体的Id(例如ThreadId、PostId...)是唯一的,但它可能与其他数据源获取的实体的Id冲突。例如,forum1 和forum2 都可以有一个Threadid=1 的线程:
我正在使用Linq2Sql 和存储库模式将我的应用程序连接到数据库。我读到,使用 Linq2Sql 时应避免使用复合键(ThreadId 和 DatasourceId 之间)。因此,我猜代理主键是我唯一的选择(是吗?):
表线程:
- UniqueId - int,PK
- DatasourceId - int
- ThreadId - int
- ...
表帖子:
- UniqueId - int,PK
- DatasourceId - int
- PostId - int
- ThreadId - int, FK 到 Threads.ThreadId
现在,我的问题是:Linq2Sql 是否能够在其生成的类中映射帖子和线程之间的 1:1 关系? 如果帖子具有 Thread.ThreadId 的外键,并且有两个实体具有相同的 ThreadId(当然,但 DatasourceId 不同),会发生什么情况?我想这将返回帖子上分配的线程的集合 - 这是我不想要的!我能否以某种方式仍然为每个帖子返回一个线程,即共享相同 DatasourceId 的帖子?
Image that I have a huge database which stores threads and posts from different datasources like two different forums. For each datasource, the Id of the entity (e.g. ThreadId, PostId...) is unique but it may collide with the Id of an entity obtained by another datasources. For example, both forum1 and forum2 can have a thread with Threadid=1:
I am using Linq2Sql and a repository pattern to connect my application to the database. I read that composite keys (between ThreadId and DatasourceId) should be avoided when using Linq2Sql. Therefore I guess that a surrogate primary key is my only option (is it?):
Table Threads:
- UniqueId - int, PK
- DatasourceId - int
- ThreadId - int
- ...
Table Posts:
- UniqueId - int, PK
- DatasourceId - int
- PostId - int
- ThreadId - int, FK to Threads.ThreadId
Now, my question is: Will Linq2Sql be able to map 1:1 relations between posts and threads in its generated classes?
What happens if a post has a foreign key to Thread.ThreadId and if there are two entities with the same ThreadId (but different DatasourceIds, of course)? I guess this will return a collection of assigned threads on the post - which I don't want! Can I somehow still return a single thread for each post which is the one which shares the same DatasourceId?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你是对的,LinqToSql 不会知道某个 Threadid 是唯一的。您可以通过在每个查询的 where 子句中包含 Datasourceid 来完成此操作
You are right that LinqToSql won't know that a certain Threadid is unique. You can do this by including the Datasourceid in your where clause in each query