简体   繁体   中英

Configuration Entity framework table using fluent API internal class

I have a class and I want to generate a table in database using this class. If I use separate class to configuration this table it works correctly when I want to Configuration this table with two column as key using internal class it has an error:

one or more validation errors were detected during model generation. StoreKabir.Models.Company :: entitytype 'Company' has no key defined. Defined the key for this 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; }
    }
}

Seems to me you need to put an attribute [Key] on your first property, CompanyId.

Not sure if EF can get it from context if it is not named Id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM