多个对象集的相同类型的 [英] Multiple object sets of the same type
问题描述
我试图创造EF5 RC类似这样的数据上下文:
类WordContext:的DbContext {
公共DbSet< Word和GT; PossibleWords {搞定;组; }
公共DbSet< Word和GT; UsedWords {搞定;组; }
}
当我试图更新数据库,我收到一个异常说:每种类型的多个对象集,不支持。该对象集PossibleWords'和'UsedWords可以同时包含类型'TestProject.Word的实例。的
一些google搜索后,看来一个结构像这样的数据上下文实际上不可能在EF
我的问题是:什么是好的代码,第一个设计来存储这样的数据
我猜是小事一桩可能是这样的:
类WordContext:{的DbContext
公共DbSet<单词GT;个字{搞定;组; }
}
类词{
公众诠释ID {搞定;组; }
公众的IList<串GT; PossibleWords {搞定;组; }
公众的IList<串GT; UsedWords {搞定;组; }
}
但是,这只是感觉可怕
编辑:当然,另一种很普通的是使用2种不同的Word类型,如
类PossibleWord {。 ..}
类BannedWord {...}
其实,现在我把它写下来,它甚至不看坏,嗯...
EDIT2:
以防万一别人运行到这个也是,我将展示它是如何解决中底:
类字{
[关键]
公共字符串字符串{搞定;组; }
}
类PossibleWord:字{}
类UsedWord:字{}
类WordContext:的DbContext {
公共DbSet< PossibleWord> PossibleWords {搞定;组; }
公共DbSet< UsedWord> UsedWords {搞定;组; }
}
想必你想代表你的原码2个不同的表。我会考虑两个类,UsedWord和PossibleWord,只是有两个人实现共同的接口,说:IWord?或者更简单的,只是有一个布尔IsUsed领域的话语,一个表/类型。
I tried to create a data context in EF5 RC similar to this:
class WordContext : DbContext {
public DbSet<Word> PossibleWords { get; set; }
public DbSet<Word> UsedWords { get; set; }
}
When I tried to update the database, I received an exception saying: Multiple object sets per type are not supported. The object sets 'PossibleWords' and 'UsedWords' can both contain instances of type 'TestProject.Word'.
After some googling, it appears that structuring a data context like this is not actually possible in EF.
My question is: What's a good code-first design to store data like this?
I guess a trivial one could be something like:
class WordContext : DbContext {
public DbSet<Words> Words { get; set; }
}
class Words {
public int ID { get; set; }
public IList<string> PossibleWords { get; set; }
public IList<string> UsedWords { get; set; }
}
But this just feels terrible.
Edit: Of course, another trivial one would be to use 2 different Word types, like
class PossibleWord { ... } class BannedWord { ... }
Actually, now that I wrote it down it doesn't even look that bad, hmm...
Edit2:
Just in case someone else runs into this too, I'll show how it was solved in the end:
class Word {
[Key]
public string String { get; set; }
}
class PossibleWord : Word { }
class UsedWord : Word { }
class WordContext : DbContext {
public DbSet<PossibleWord> PossibleWords { get; set; }
public DbSet<UsedWord> UsedWords { get; set; }
}
Presumably you are trying to represent 2 different tables in your original code. I would consider two classes, UsedWord and PossibleWord, and just have both of them implement a common interface, say: IWord? Or simpler, just have a bool "IsUsed" field on Word, and one table/type.
这篇关于多个对象集的相同类型的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!