2017-09-15 167 views
0

我正在嘗試使用枚舉類(link)來代替枚舉和「查找表」。AutoMapping枚舉類

我有這種情況,它顯示了我的視圖中的一個簡單的列表,我想從枚舉類而不是StatusId顯示TaskStatus名稱,但我得到這個錯誤「InvalidOperationException:實體類型'TaskStatus'需要一個主鍵被定義爲。」

我的方法都錯了嗎?

<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

您的問題與Automapper無關。您收到的錯誤消息來自EntityFramework。由於您在實體中定義了Status屬性,因此EF正在嘗試將TaskStatus類作爲另一個實體處理,並且由於它沒有主鍵,因此錯誤消息指出它不能。

如果你使用枚舉類死心塌地看看here標題下的「封裝原語(又名NodaTime /枚舉類的問題)」

試着改變你的代碼是這樣的:

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