运行时: netcoreapp2.0
ASP.Net Core: 2.0.1
EF Core: 2.0.1
Microsoft.EntityFrameworkCore.SqlServer: 2.0.1
我正在处理一个被许多服务使用的旧数据库,原始创建者将某个表的主键定义为 short 类型,而对该表的外键则定义为 int 类型。我是否有可能处理这种情况呢?
注意:目前不可行更改列类型。
考虑以下两个类:
public class Database {
public short DatabaseId { get; set; }
public Database { get; set; }
}
public class Client {
public int ClientId { get; set; }
public int DatabaseId { get; set; }
public Database Database { get; set; }
}
我的第一次尝试:
public int DatabaseId { get; set; }
[ForeignKey("DatabaseId")] public Database Database { get; set; }
抛出(throws)
System.InvalidOperationException: The relationship from 'Client.Database' to 'Database.Client' with foreign key properties {'DatabaseId' : int} cannot target the primary key {'DatabaseId' : short} because it is not compatible. Configure a principal key or a set of compatible foreign key properties for this relationship.
现在使用流畅的API:
使用流畅的API现在:
modelBuilder.Entity<Client>(table => {
table.HasOne(p => p.Database)
.WithOne(i => i.Client)
.HasForeignKey<Client>(c => c.DatabaseId)
.HasPrincipalKey<Database>(d => d.DatabaseID);
});
定义阴影属性失败
modelBuilder.Entity<Client>(table => {
table.Property<int>("DatabaseId");
table.HasOne(p => p.Database)
.WithOne(i => i.Client)
.HasForeignKey("DatabaseId")
.HasPrincipalKey<Database>(d => d.DatabaseId);
});
抛出异常
System.InvalidOperationException: You are configuring a relationship between 'Client' and 'Database' but have specified a foreign key on 'DatabaseId'. The foreign key must be defined on a type that is part of the relationship.
好的,这次没有阴影属性:
modelBuilder.Entity<Client>(table => {
table.HasOne(p => p.Database)
.WithOne(i => i.Client)
.HasForeignKey<Client>(c => c.DatabaseId)
.HasPrincipalKey<Database>(d => d.SQLDatabaseID);
});
抛出异常。
System.InvalidOperationException: The types of the properties specified for the foreign key {'DatabaseId'} on entity type 'Client' do not match the types of the properties in the principal key {'DatabaseID'} on entity type 'Database'.
于是,我试着只改变实体类型,希望EF可以将int映射为int16。
public class Client {
public int ClientId { get; set; }
public short DatabaseId { get; set; } // <-- now a short
public Database Database { get; set; }
}
抛出(throws)
System.InvalidOperationException: An exception occurred while reading a database value for property 'Client.DatabaseId'. The expected type was 'System.Int16' but the actual value was of type 'System.Int32'. ---> System.InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.Int16'.
我开始感觉这似乎是不可能的。