Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple object sets of the same type

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; }
}
like image 883
user974608 Avatar asked Aug 11 '12 10:08

user974608


1 Answers

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.

like image 192
Marc Gravell Avatar answered Nov 15 '22 15:11

Marc Gravell