我有一个类,我想使用这个类在数据库中生成一个表。如果我使用单独的类来配置此表,当我想使用内部类将两列作为键配置此表时,它会正常工作,它有一个错误:
在模型生成期间检测到一个或多个验证错误。StoreKabir.Models.Company :: 实体类型"Company"未定义键。定义了此实体类型的键
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StoreKabir.Models
{
class Company
{
internal class Configuration : System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<Company>
{
public Configuration()
{
#region TableCompanyConfiguration
ToTable("Companies");
HasKey(current => new
{
current.CopmanyId,
current.CompanyName
});
Property(current => current.CopmanyId)
.HasColumnName("CopmanyId")
.HasColumnOrder(0)
.IsRequired()
.HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None);
Property(current => current.CompanyName)
.HasColumnName("CompanyName")
.HasColumnOrder(1)
.IsRequired()
.IsVariableLength()
.IsUnicode(true)
.HasMaxLength(40);
#endregion TableCompanyConfiguration
}
}
public Company()
{
}
public Company(Int64 companyId, string companyName)
{
CopmanyId = companyId;
CompanyName = companyName;
}
public Int64 CopmanyId { get; set; }
public string CompanyName { get; set; }
}
}
在我看来,
您需要在您的第一个属性 CompanyId 上放置一个属性 [Key]。
不确定 EF 是否可以从上下文中获取它(如果它未命名为 Id(。