![](/img/trans.png)
[英]Creating composite primary key consisting off foreign keys in fluent API with ASP.NET core
[英]ASP.NET add migration 'composite primary key error' how to use fluent API
您好,我正在創建 Web 應用程序,並且已經安裝了Microsoft.entityFrameworkCore和Microsoft.entityFrameworkCore.Tools 。
在包管理器控制台中執行添加遷移的過程中,我收到一個錯誤
" System.InvalidOperationException: 實體類型 'Attends' 具有使用數據注釋定義的復合主鍵。要設置復合主鍵,請使用 fluent API "
這是我在實體文件夾中的代碼。
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace _3241_farmDb.Entities
{
public class Farm
{
[Required, MaxLength(30)]
[Key]
public string FarmName { get; set; }
[Required, MaxLength(15)]
public string FarmCity { get; set; }
[Required, MaxLength(9)]
public string FarmerSSN { get; set; }
}
public class Farmer
{
[Required, MaxLength(9)]
[Key]
public int SS { get; set; }
[Required, MaxLength(9)]
public string Fname { get; set; }
[Required, MaxLength(15)]
public string Lname { get; set; }
[Required, MaxLength(15)]
public string CityName { get; set; }
[Required, MaxLength(15)]
public string Address { get; set; }
[Required, MaxLength(30)]
public string BoardPositionName { get; set; }
}
public class Child
{
[Required, MaxLength(9)]
[Key]
public int FarmerSS { get; set; }
[Required, MaxLength(15)]
[Key]
public string Fname { get; set; }
[Required, MaxLength(15)]
[Key]
public string Lname { get; set; }
[Required]
public int Age { get; set; }
}
public class Attends
{
[Key, Column(Order = 1)]
public int FarmerSS { get; set; }
[Key, Column(Order = 2)]
public int HotelID { get; set; }
[Required, MaxLength(15)]
public string BoardPosition { get; set; }
}
public class Livestock
{
[Required, MaxLength(15)]
public int LivestockID { get; set; }
[Required, MaxLength(15)]
public string LivestockType { get; set; }
}
public class Farm_Houses
{
[Required, MaxLength(15)]
[Key]
public int LivestockID { get; set; }
[Required, MaxLength(15)]
public string FarmName { get; set; }
}
public class Crops
{
[Required, MaxLength(15)]
[Key]
public int CropID { get; set; }
[Required, MaxLength(15)]
public string CropName { get; set; }
}
}
如何調整它以正確設置復合鍵?
在EF 核心上..
復合鍵只能使用 Fluent API 進行配置 - 約定永遠不會設置復合鍵,並且您不能使用數據注釋來配置一個。
這是Fluent API版本:
注意:這只是一個例子。 請根據您的用例進行調整。
// (In the DbContext subclass)
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Attends>()
.HasKey(c => new { c.FarmerSS, c. HotelID });
}
您可以在此處閱讀更多相關信息: 復合鍵
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.