views:

211

answers:

2

I'm having an issue with tables that have foreign keys to other tables in a different schema.

For example, TableA in SchemaA has a foreign key to TableB in SchemaB. When CTP4 creates the database, instead of creating a foreign key from TA to TB, it creates a third table "TableA_TableB" with columns TableA_ID and TableB_ID as if it thinks that it should be a many to many relationship.

public class TableA 
{ 
  public int ID { get; set; } 
  public TableB TableB { get; set; } 
}

public class TableB
{ 
  public int ID { get; set; } 
}

var builder = new ModelBuilder();

// this works fine - creates only two tables with the correct foreign key
// builder.Entity<TableA>();
// builder.Entity<TableB>();

// this doesn't work - creates a third many-to-many table
builder.Entity<TableA>().MapSingleType()
  .ToTable( new StoreTableName( "TableA", "SchemaA" ) );
builder.Entity<TableB>().MapSingleType()
  .ToTable( new StoreTableName( "TableB", "SchemaB" ) );

var model = builder.CreateModel();

var store = new DbContext( "database", model );
store.Database.DeleteIfExists();
store.Database.Create();

If I remove the .ToTable.. from the above code, it creates the tables correctly.

I tried looking for a solution but couldn't find anything. Any idea what I'm doing wrong, or is this a bug?

A: 

Can you try the following:

builder.Entity<TableA>().HasKey(t => t.ID);
builder.Entity<TableA>().HasRequired(tA => tA.TableB);
builder.Entity<TableB>().HasKey(t => t.ID);
TheCloudlessSky
The mappings such as your example work find when I don't use a different schema. Once I add the different schemas for each table, that's when it doesn't work.
mjezzi
@mjezzi - Hmm...Try to make a post on the official MSDN forums.
TheCloudlessSky
@TheClouslessSky That's a good idea.
mjezzi
@mjezzi - Sorry I couldn't be more help but the solution I posted *should* work... Because this is still a CTP, we don't have a lot of documentation.
TheCloudlessSky
+2  A: 

Hi,

This turned out to be a bug in CTP4, the code you have posted should work as you expected. The workaround for the moment is to explicitly map the columns in TableA:

builder.Entity<TableA>().MapSingleType(a => new { a.ID, tableBID = a.TableB.ID })
    .ToTable(new StoreTableName("TableA", "SchemaA"));

~Rowan

Rowan Miller
That did the trick!
mjezzi