开发者

Entity Framework CTP4 - Foreign key mappings across schemas don't work properly. Bug?

开发者 https://www.devze.com 2023-01-09 17:37 出处:网络
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, i

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 id开发者_如何学Goea what I'm doing wrong, or is this a bug?


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


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消