【问题标题】:Configuration Entity framework table using fluent API internal class使用fluent API内部类配置实体框架表
【发布时间】:2018-04-17 12:19:36
【问题描述】:

我有一个类,我想使用这个类在数据库中生成一个表。 如果我使用单独的类来配置此表,则当我想使用内部类以两列作为键配置此表时,它会正常工作,则会出现错误:

在模型生成过程中检测到一个或多个验证错误。 StoreKabir.Models.Company :: entitytype 'Company' 没有定义键。定义了这个 EntityType 的键

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; }
    }
}

【问题讨论】:

  • 这里没有人吗?

标签: c# configuration fluent


【解决方案1】:

在我看来,您需要在您的第一个属性 CompanyId 上放置一个属性 [Key]。

如果 EF 未命名为 Id,则不确定 EF 是否可以从上下文中获取它。

【讨论】:

  • 如果我想将这两列都用作键呢:HasKey(current => new { current.companyName, current.companyId});
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多