3
是否有可能通過流利的映射API向實體框架添加一個列到特定的表,而沒有模型類中的相應屬性?實體框架:在模型類中創建沒有屬性的數據庫列
是的,我可以通過在遷移中執行SQL腳本來實現這一目標,但我更願意在模型配置中指定而不是在遷移中指定。
是否有可能通過流利的映射API向實體框架添加一個列到特定的表,而沒有模型類中的相應屬性?實體框架:在模型類中創建沒有屬性的數據庫列
是的,我可以通過在遷移中執行SQL腳本來實現這一目標,但我更願意在模型配置中指定而不是在遷移中指定。
我一直在尋找這一點,誠然是爲了解決EF核心發佈之前沒有原生價值對象(複雜屬性)處理的問題。
Shadow properties是一種指定從此上下文生成的遷移應該將列添加到數據庫的方法。具體看我的例子:
// In DbContext-inheriting class:
protected override void OnModelCreating(ModelBuilder builder)
{
// Ignore the model property that holds my valueobject -
// (a complex type encapsulating geolocation latitude/longitude)
var entityBuilder = builder.Entity<Item>()
.Ignore(n => n.Location);
// Add shadow properties that are appended to the table in the DB
entityBuilder.Property<string>("Latitude");
entityBuilder.Property<string>("Longitude");
base.OnModelCreating(builder);
}
這會產生遷移表創建語句如下:
migrationBuilder.CreateTable(
name: "Items",
columns: table => new
{
Key = table.Column<string>(nullable: false),
Latitude = table.Column<double>(nullable: false),
Longitude = table.Column<double>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Items", x => x.Key);
});
對於EF Core的解決方案,雖然無法接受您的答案,因爲我正在尋找適用於EF 6.1.3的解決方案。不過,感謝您發佈這個內容 - 切換到EF Core時,我一定會使用它。 –
EF哪個版本的? –
@PaulZahra 6.1.3 –