Context: ASP.NET MVC 2.0, Linq-to-Sql, .Net 3.5, IIS7, MS SQL 2008
I'm working on a game fan site.
I have a table as follows:
ToonId int (primary key)
RealmId (FK into Realms table)
OwnerId int (FK into Users table)
ToonName nvarchar(50)
IsMain bit
That is a single user may own multiple toons on multiple realms (aka servers), but exactly one toon must be marked as main per user per realm (only for realms where there is at least one toon).
Suppose I have two toons (on one realm):
Foo (marked as main)
and
Bar (not main)
I want to change my main, and for that I do something like: Foo.IsMain = false Bar.IsMain = true
I'm using Linq-to-SQL.
Question: how can I make said transition without entering a state when I have either more than one or zero main toons.
Note: I have a materialized view (filtered by IsMain = 1) that defines a composite key (OwnerId, RealmId), as such when I do main-toon transition I get "unique key violation" exception from that materialized view.
I have tried using transaction, but I still get exception on 'db.SubmitChanges()'.
Option 2: I suspect that I have the flaw in the database design (what's the name of this flaw?). Should I create a mapping table?
OwnerId, RealmId -> ToonId