实体类型“ xxx”需要主键,但是我已经定义了主键?

时间:2019-05-06 09:04:53

标签: c# entity-framework asp.net-core

我的实体是从Entity类派生的,因此默认情况下它应具有int类型的id,但是由于某些原因,EntityFramework无法识别它。我什至尝试手动设置主键(注释掉),但仍然无法使用。

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
using Abp.Timing;

namespace Test.Models
{

    [Table("AppTasks")]
    public class Task : Entity, IHasCreationTime
    {
        //[Key]
        //public int Id { get; set; }

        public const int MaxTitleLength = 256;
        public const int MaxDescriptionLength = 64 * 1024;



        [Required]
        [StringLength(MaxTitleLength)]
        public string Title { get; set; }


        [StringLength(MaxDescriptionLength)]
        public string Description { get; set; }

        public TaskState State { get; set; }

        public DateTime CreationTime { get; set; }

        public Task()
        {
            CreationTime = Clock.Now;
            State = TaskState.Open;
        }

        public Task(string title, string description = null) : this()
        {
            Title = title;
            Description = description;
        }
    }

    public enum TaskState : byte
    {
        Open = 0,
        Completed = 1
    }
}

1 个答案:

答案 0 :(得分:0)

尝试使用具体的IEntityTypeConfiguration<T>

public class TaskConfiguration : IEntityTypeConfiguration<Task>
{
    public void Configure(EntityTypeBuilder<Task> builder)
    {
        builder.HasKey(tsk => tsk.Id);
        //builder.HasMany(...) relationships et al.
    }
}

在您的DbContext定义(或您所说的任何定义)中:

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);
    builder.ApplyConfiguration(new TaskConfiguration());
}

这绝对应该以某种方式配置EFCore,Id将成为该实体的主键。另外一个好处是,您将获得更多的灵活性和更简洁的代码。