我試圖用實體框架代碼優先(包括流利的API映射)方法創建一對一的映射。這是我第一次使用代碼優先的方法。實體框架代碼優先方法一對一流暢的api映射
當我運行UpdateTaskCompleted()
方法,它會拋出以下異常:
操作數類型衝突:唯一標識符是與詮釋
我懷疑我做錯了流利的API不兼容映射。
[Table("tblSession")]
public partial class tblSession
{
[Key]
public Guid SessionId { get; set; }
[Required]
public bool IsActive { get; set; }
public tblTaskDetail tblTaskDetail { get; set; }
}
[Table("tblTaskDetail")]
public partial class tblTaskDetail
{
[Key]
public int TaskDetailID { get; set; }
public Guid? SessionID { get; set; }
[Required]
[StringLength(50)]
public string TaskStatus { get; set; }
[ForeignKey("SessionID")]
public tblSession tblSession { get; set; }
}
public class RequestSession
{
[Key]
public Guid SessionId { get; set; }
public bool IsActive { get; set; }
public TaskDetail TaskDetail { get; set; }
}
public class TaskDetail
{
[Key]
public int TaskDetailID { get; set; }
public Guid? SessionID { get; set; }
public string TaskStatus { get; set; }
public RequestSession RequestSession { get; set; }
}
public class TaskDetailMapper:EntityTypeConfiguration<TaskDetail>
{
public TaskDetailMapper()
{
this.ToTable("tblTaskDetail");
this.HasKey(hk => hk.TaskDetailID);
HasRequired<RequestSession>(a => a.RequestSession)
.WithRequiredPrincipal(o => o.TaskDetail).Map(m => m.MapKey("SessionID"));
this.Property(o => o.TaskStatus).HasColumnName("TaskStatus");
}
}
public class RequestSessionMapper : EntityTypeConfiguration<RequestSession>
{
public RequestSessionMapper()
{
// Table & Column Mappings
this.ToTable("tblSession");
//Primary key
this.HasKey<Guid>(hk => hk.SessionId);
this.Property(t => t.SessionId).HasColumnName("SessionId");
this.Property(t => t.IsActive).HasColumnName("IsActive");
}
}
public partial class WarehouseAPIContext : DbContext
{
public WarehouseAPIContext(): base("name=WarehouseAPIContext")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new RequestSessionMapper());
modelBuilder.Configurations.Add(new TaskDetailMapper());
}
}
public TaskDetail UpdateTaskCompleted(TaskDetail entity)
{
try
{
var entry = dbSet.Find(entity.TaskDetailID);
entry.TaskStatus = entity.TaskStatus;
entity.RequestSession = new RequestSession()
{
IsActive = false
};
_context.SaveChanges();
return entity;
}
catch (Exception ex)
{
throw ex;
}
}