【发布时间】:2019-07-19 14:40:01
【问题描述】:
我想在不丢失数据的情况下扩展两个实体之间的现有关系。那就是 ASP.NET Core 2.0 Web 应用程序。
我有Cars 和Navs(GPS 装置)。特定的Car 可以有一个特定的Nav,反之亦然特定的Nav 可以在特定的汽车中。但是,Nav 可能在仓库中,因此它不在任何 Car 中,并且特定 Car 目前不能有任何 Nav。当然,特定的Nav 最多可以在 1 辆汽车中,特定的汽车最多可以有 1 个导航。
我在Navs 和Cars 之间建立了关系。我还想添加 Cars 和 Navs 之间的关系,以便轻松地从 Car 级别的数据中提取有关 Nav 目前存在的系统(如果有的话)。
现在我有以下设置:
public class Car
{
public int ID { get; set; }
public string ModelName { get; set; }
//other properties
}
public class Nav
{
public int ID { get; set; }
public decimal ScreenSize { get; set; }
//other properties
public virtual Car Car { get; set; }
}
我想做的就是添加到Car 类:
public virtual Nav Nav { get; set; }
但是当我运行Add-Migration 时,它会降低当前关系,所以如果我理解正确,我会丢失我目前拥有的所有数据......这就是我在AddMigration 之后得到的:
migrationBuilder.DropForeignKey(
name: "FK_Navs_Cars_CarID",
table: "Navs");
migrationBuilder.DropIndex(
name: "IX_Navs_CarID",
table: "Navs");
migrationBuilder.DropColumn(
name: "CarID",
table: "Navs");
migrationBuilder.AlterColumn<int>(
name: "ID",
table: "Navs",
nullable: false,
oldClrType: typeof(int))
.OldAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
migrationBuilder.AddForeignKey(
name: "FK_Navs_Cars_ID",
table: "Navs",
column: "ID",
principalTable: "Cars",
principalColumn: "ID",
onDelete: ReferentialAction.Cascade);
维护当前关系和数据并从另一方添加关系的最佳方式是什么?
添加说明:
使用当前关系,我可以轻松地从 Nav 级别提取有关 Car 的数据:
var modelName = nav.Car != null ? nav.Car.ModelName : "";
我也想以其他方式做同样的事情:
var screenSize = car.Nav != null ? car.Nav.ScreenSize : 0;
【问题讨论】:
-
请同时显示您打算制作的模型+新旧映射。
-
@GertArnold 如前所述,我想稍微修改 Car 类,添加:
public virtual Nav Nav { get; set; },但是当我这样做时,Add-Migration 会丢弃当前 FK...现在我可以轻松从导航级别提取 Car 的数据,例如:var modelName = nav.Car != null ? nav.Car.ModelName : ""。我也想以其他方式这样做:var screenSize = car.Nav != null ? car.Nav.ScreenSize : 0。希望它能澄清主题。
标签: c# asp.net-core entity-framework-core