Entity Framework 4.0 使用非主键的多对多关系
我正在尝试使用 Entity Framework 4.0 使用我继承的遗留 MS SQL 数据库构建通用存储库。相当熟悉的场景。
我需要将类别信息添加到相当长的现有项目列表中。
这些项目可以同时属于多个类别,因此我创建了一个名为 CategoryMapping 的映射表
不幸的是,SchemaDefinitionCode不是唯一的,不能成为数据库中的外键(FK)。
我尝试将我自己的部分类添加到 DefinitionSchema 实体,但由于它没有索引,这会对性能造成严重影响。 用于测试的演示代码,我不想每次加载此代码时都创建一个新的上下文:
public partial class DefinitionSchema
{
private MyEntities context;
public IQueryable<Category> Categories
{
get
{
context = new MyEntities();
var categories = context.Categories
.Where(c => c.CategoryMappings
.Where(m => m.SchemaDefinitionCode == this.SchemaDefinitionCode).Any());
return categories;
}
}
}
然后我可以像这样调用一个项目列表:
var q = context.SchemaDefinitions
.Where(s => s.Categories
.Where(c => c.Name == category)
.Any()
);
How can I link my table andapping in the most有效的方式而不清除现有的数据库结构?
I am trying to build a generic repository using Entity Framework 4.0 using a legacy MS SQL database I have inherited. A pretty familiar scenario.
I need to add category information to a fairly long list of existing items.
The items can belong to several categories at the same time so I created an mapping table called CategoryMapping
Unfortunately SchemaDefinitionCode is not unique and cannot be made into a Foreign Key (FK) in the database.
I have tried to add my own partial class to the DefinitionSchema entity but as it's not indexed, this has a severe performance hit. Demo code for testing, I won't want to create a new context every time I load this:
public partial class DefinitionSchema
{
private MyEntities context;
public IQueryable<Category> Categories
{
get
{
context = new MyEntities();
var categories = context.Categories
.Where(c => c.CategoryMappings
.Where(m => m.SchemaDefinitionCode == this.SchemaDefinitionCode).Any());
return categories;
}
}
}
I can then call a list of items like so:
var q = context.SchemaDefinitions
.Where(s => s.Categories
.Where(c => c.Name == category)
.Any()
);
How can I link my tables and mapping in the most efficient manner without wiping out the existing database structure?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它不能以这种方式工作,因为 EF 不支持唯一键,并且
SchemaDefinitionCode
必须是唯一的才能与Category
形成有效的多对多关系。如果您的SchemaDefinitionCode
在DefinitionSchema
表中不唯一,则它不能用作与CatagoryMapping
关系中的主体。如果它是唯一的,您可以使用SchemaDefinitionID
代替,因为不会有多个 Id 具有相同的代码值。It can't work this way because EF doesn't support unique keys and
SchemaDefinitionCode
must be unique to form valid many-to-many relation withCategory
. If yourSchemaDefinitionCode
is not unique inDefinitionSchema
table it can't be used as principal end in the relation withCatagoryMapping
. If it is unique you can useSchemaDefinitionID
instead because no more then one Id will have the same code value.