我正在尝试定义一个客户可以拥有0或1个地址的关系。对于这种关系,我希望在“地址”表中使用customerId,但不希望在“客户”表中使用addressId。听起来很简单?我已经看过示例,但是在OnModelCreating中缺少了诸如hasForeignKey或hasOptional之类的某些属性,因此我没有看过其他示例。我正在使用EF Core 3.15版。不管我尝试什么,迁移都会向“客户”表添加一个addressId列。我希望能够使用sql语句“从地址删除”删除所有地址
这是我的2个实体
public class AddressEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid AddressId { get; set; }
public string Line1 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public string Country { get; set; }
public virtual Guid Customer { get; set; }
}
public class CustomerEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid CustomerId { get; set; }
public string CustomerName { get; set; }
public string CustomerEmail { get; set; }
public virtual AddressEntity Address { get; set; }
}
这是我的迁移代码
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Addresses",
columns: table => new
{
AddressId = table.Column<Guid>(nullable: false),
Line1 = table.Column<string>(nullable: true),
City = table.Column<string>(nullable: true),
State = table.Column<string>(nullable: true),
PostalCode = table.Column<string>(nullable: true),
Country = table.Column<string>(nullable: true),
Customer = table.Column<Guid>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Addresses", x => x.AddressId);
});
migrationBuilder.CreateTable(
name: "Customers",
columns: table => new
{
CustomerId = table.Column<Guid>(nullable: false),
CustomerName = table.Column<string>(nullable: true),
CustomerEmail = table.Column<string>(nullable: true),
AddressId = table.Column<Guid>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Customers", x => x.CustomerId);
table.ForeignKey(
name: "FK_Customers_Addresses_AddressId",
column: x => x.AddressId,
principalTable: "Addresses",
principalColumn: "AddressId",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Customers_AddressId",
table: "Customers",
column: "AddressId");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句