gpt4 book ai didi

c# - ASP.NET 添加迁移 'composite primary key error' 如何使用 Fluent API

转载 作者:IT王子 更新时间:2023-10-29 03:48:49 25 4
gpt4 key购买 nike

您好,我正在创建 Web 应用程序,并且已经安装了 Microsoft.entityFrameworkCoreMicrosoft.entityFrameworkCore.Tools

在包管理器控制台中执行添加迁移的过程中出现错误

System.InvalidOperationException:实体类型‘Attends’具有用数据注释定义的复合主键。要设置复合主键,请使用流畅的 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 核心 ..

Composite keys can only be configured using the Fluent API -conventions will never setup a composite key and you can not use DataAnnotations to configure one.

这是 Fluent API 版本:

注意:这只是一个例子。请根据您的用例进行调整。

// (In the DbContext subclass)
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Attends>()
.HasKey(c => new { c.FarmerSS, c. HotelID });
}

您可以在这里阅读更多相关信息:composite key

关于c# - ASP.NET 添加迁移 'composite primary key error' 如何使用 Fluent API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40898365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com