[英]Entity Framework code-first approach one-to-one fluent api mapping
我正在尝试使用Entity Framework代码优先(包括流畅的API映射)方法创建一对一的映射。 这是我第一次使用代码优先方法。
当我运行UpdateTaskCompleted()
方法时,它将引发以下异常:
操作数类型冲突:uniqueidentifier与int不兼容
我怀疑我在流畅的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;
}
}
TaskDetail.Id的类型为int,Session.Id的类型为Guid。
首先,我将选择使用Annotation或FluentAPI来配置模型。 在某些极端情况下,只能用一种方法来完成功能,而不能用另一种方法来完成,但是这些情况很少,只有很少的一部分并且有据可查。
我使用FluentAPI是因为它更具表现力,并且允许将所有配置都放在一个位置。
您需要在这里做的是检查关于EF关系的很好的资源: http : //www.entityframeworktutorial.net/entity-relationships.aspx
任何实体框架问题/功能的google都将在第一页上显示该网站的最佳搜索结果-花费一些时间并进行大量研究,然后再提出问题-每个人都非常乐意为您提供答案,但是通过研究和寻找解决问题的方法的阅读材料是真正的价值所在,因为您将学到更多的知识,而不仅仅是如何解决当前的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.