I need to define a unique index over two columns (link columns in a junction table) in Orchard's migrations file. I've found a similar question, but it's unanswered, except for a comment stating that adding a unique index after creation of the table is prohibited. However, my problem is not this - I will rebuild my tables before the database goes live anyway, so I do everything in the Create()
method. I tried few variants of what I found and I always got syntax errors, so I guess Orchard uses (slightly?) different syntax than Ruby on Rails.
I don't consider making the indexes in the SQL Server database (dirty - Orchard is likely to get confused by this) and I don't like checking the uniqueness in controllers/services (I already made quite a lot of code, hard to maintain and probably slow, and just found another dupe).
EDIT: I found that there are no foreign keys in the database. Combined with the Orchard guide to foreign keys, it seems that Orchard prefers doing things in the code only, bypassing the strong points of databases such as proper foreign keys and multiple primary keys (I know they were discouraged somewhere, otherwise I would try go this way from the start). However, as someone with more SQL than ordinary programming experience, I would prefer to exploit proper keys and indexes as much as possible, unless heavily "non-orchardy". If avoiding the database tools has some good reason, please explain why, and sketch the Orchard way of assuring uniqueness of junction table records.
What I tried:
SchemaBuilder.CreateTable(typeof(FooBarRecord).Name, table => table .Column("Id", column => column.PrimaryKey().Identity()) .Column("Foo_Id", column => column.NotNull().Unique()) .Column("Bar_Id", column => column.NotNull().Unique()) );
This is not what I want - I need to connect each foo
with several rows of bar
and vice versa. So I tried the ruby-on-rails solution:
add_index :FooBarRecord, [:Foo_Id,:Bar_Id], :unique => true
and it returned syntax errors at most columns and brackets. The same when I wrapped it in an AlterTable:
SchemaBuilder.AlterTable(FooBarRecord,
table => table
add_index [:Foo_Id, :Bar_Id], :unique => true
);
The same when I formatted the table name differently:
SchemaBuilder.AlterTable(typeof(FooBarRecord).Name,
table => table
add_index [:Foo_Id, :Bar_Id], :unique => true
);
Here is the model:
public class FooBarRecord
{
public virtual int Id { get; set; }
public virtual RoleRecord Role { get; set; }
public virtual EvidenceRecord Evidence { get; set; }
public virtual bool EditPermission { get; set; }
}