Hello I am in the process of creating a Web Application and have already installed both the Microsoft.entityFrameworkCore and Microsoft.entityFrameworkCore.Tools.
During the process of executing an add-migration in the package manager console I get an error
"System.InvalidOperationException: Entity type 'Attends' has composite primary key defined with data annotations. To set composite primary key, use fluent API"
Here is my code in the entity folder.
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; }
}
}
How do I adjust it to set the composite key properly?
On EF core ..
Composite keys can only be configured using the Fluent API - conventions will never setup a composite key and you can not use Data Annotations to configure one.
Here is the Fluent API version :
Note: This is just an example. Please adjust it according to your use case.
// (In the DbContext subclass)
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Attends>()
.HasKey(c => new { c.FarmerSS, c. HotelID });
}
You can read more about it here : composite key