我尝试使用枚举类(link)代替枚举和"查找表"。
我有这个场景,在我的视图中显示一个简单的列表,我想在枚举类而不是StatusId中显示TaskStatus名称,但是我得到了这个错误" InvalidOperationException:实体类型' TaskStatus& #39;需要定义主键。"
我的方法是不是错了?
<table clss="table">
@foreach(var item in Model)
{
<tr>
<td>@item.Id</td>
<td>@item.Name</td>
<td>@item.Status</td>
</tr>
}
</table>
public class Tasks : BaseEntity
{
public string Name { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? DueDate { get; set; }
public byte StatusId { get; set; }
public string AssignedTo { get; set; }
public virtual TaskStatus Status { get; set; }
}
public class IndexVm
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? DueDate { get; set; }
public byte StatusId { get; set; }
public TaskStatus Status { get; set; }
}
public class TaskStatus : Enumeration<TaskStatus, int>
{
public static readonly TaskStatus NotStarted = new TaskStatus(1, "Not Started");
public static readonly TaskStatus InProgress = new TaskStatus(2, "In Progress");
public static readonly TaskStatus Completed = new TaskStatus(3, "Completed");
public static readonly TaskStatus WaitingOnSomeoneElse = new TaskStatus(4, "Waiting on someone else");
public static readonly TaskStatus Deferred = new TaskStatus(5, "Deferred");
private TaskStatus(int value, string displayName) : base(value, displayName) { }
}
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<Tasks, IndexVm>()
.ForMember(vm => vm.Status, conf => conf.MapFrom(ol => ol.Status.DisplayName));
}
}
答案 0 :(得分:0)
您的问题与Automapper无关。您收到的错误消息来自EntityFramework。因为您在实体中定义了Status
属性,所以EF正在尝试将TaskStatus
类视为另一个实体而不能,因为它没有主键,因为错误消息指出。
如果您已经设置使用Enum类,请在标题&#34; Encapsulated primitives(又名NodaTime / Enumeration类问题)&#34;
标题下查看here。尝试将代码更改为以下内容:
public class IndexVm
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? DueDate { get; set; }
public byte StatusId { get; set; }
[NotMapped]
public TaskStatus Status {
get { //Return the value of StatusVal converted to an Enumeration
set { //Set the value of StatusVal after converting from an Enumeration }
}
public int StatusVal { get; set; }
}