实体框架导航属性外键

时间:2017-03-14 19:42:31

标签: c# entity-framework

我有两个表,JobRequest和WorkOrder。 JobRequest的主键是名为RequestNumber的varchar字段。还有一个字段,与工作单表中的外键同名。该字段上的表之间存在0到1的关系;当有机维护团队无法完成作业请求时,会为另一个维护团队发出工单。

数据库看起来有点像:

JobRequest

ID        BIGINT       IDENTITY,
RequestNumber       VARCHAR(15)        NOT NULL,
...

工作单

ID        BIGINT       IDENTITY,
WONumber            VARCHAR(25)        NOT NULL,
RequestNumber       VARCHAR(15)        NULL,
...

我建立了一个模型,构建了上下文和数据库表。我先使用手动代码,所以我没有任何模板或SDL文件。

我的模特看起来像:

[Table("JobRequest")]
public partial class JobRequest
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public JobRequest()
    {
        AuditLogs = new HashSet<AuditLog>();
        AuthorizedUsers = new HashSet<AuthorizedUser>();
    }

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long? ID { get; set; }

    [Key]
    [StringLength(15)]
    [DisplayName("Request Number")]
    public string RequestNumber { get; set; }

    [NotMapped]
    public virtual WorkOrder WorkOrder { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<AuditLog> AuditLogs { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<AuthorizedUser> AuthorizedUsers { get; set; }

    ...

[Table("WorkOrder")]
public partial class WorkOrder
{
    public WorkOrder()
    {
    }

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long? ID { get; set; }

    [Key]
    [StringLength(25)]
    [DisplayName("Work Order Number")]
    public string WONumber { get; set; }

    [Key]
    [Required]
    [StringLength(15)]
    [DisplayName("Request Number")]
    public string RequestNumber { get; set; }

在上下文中我有:

    ...
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<JobRequest>()
            .HasOptional(j => j.WorkOrder);
    }
    ...

我可以轻松更新我的JobRequest表。当我从作业请求创建工作订单时,出现错误无效的列名称'WorkOrders_RequestNumber'

我做错了什么? 我需要添加CSDL文件吗?

如果我这样做,有人可以将GUMBY风格分解吗?我昨晚做了一个睡眠研究,我正在喝着不好的咖啡和肾上腺素。

编辑添加导航属性和Fluent定义。

编辑2 - 我做了Ivan Stoev(http://chat.stackoverflow.com/rooms/138056/discussion-between-russel-madere-and-ivan-stoev)建议的更改。现在一切都保存,但RequestNumber不保存在WorkOrder表中。这会在保存数据后中断关系。我可以得到关于持久化RequestNumber的建议吗?

编辑3 - 查看SQL Server Profiler,我看到以下插入语句。

exec sp_executesql N'INSERT [dbo].[WorkOrder]([WONumber], [Owner], [JobName], [SubContractNum], 
                                          [ContractAmount], [Fee], [Company], [Department], 
                                          [DisplayCompany], [StartDate], [CompletionDate], 
                                          [County], [Taxable], [PPBond], [Address], [City], 
                                          [State], [Zip], [Country], [RequestedBy], 
                                          [PurchAddress], [PurchCity], [PurchState], [PurchZip], 
                                          [PurchCounty], [PurchCountry], [DescriptionOfWork], 
                                          [EntryUser], [EntryDate], [LastChangedBy], [LastChanged], 
                                          [ContractType], [Revision], [PrintURL], [RequestNumber])
VALUES (@0, NULL, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12, @13, @14, @15, @16, 
    @17, @18, @19, @20, @21, @22, @23, @24, @25, @26, @27, @28, @29, @30, @31, @32, @33, 
    @34, NULL)
SELECT [ID]
FROM [dbo].[WorkOrder]
WHERE @@ROWCOUNT > 0 AND [WONumber] = @0'...

我从语句中删除了架构和数据特定信息。

我在这里看到ForeignKey被插入为NULL。如何设置外键的值?

1 个答案:

答案 0 :(得分:1)

以下设计表示提供的示例数据库架构:

型号:

[Table("JobRequest")]
public partial class JobRequest
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long? ID { get; set; }

    [Key]
    [StringLength(15)]
    [DisplayName("Request Number")]
    public string RequestNumber { get; set; }

    public virtual WorkOrder WorkOrder { get; set; }
}

[Table("WorkOrder")]
public partial class WorkOrder
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long? ID { get; set; }

    [Key]
    [StringLength(25)]
    [DisplayName("Work Order Number")]
    public string WONumber { get; set; }
    public virtual JobRequest JobRequest { get; set; }
}

配置:

modelBuilder.Entity<JobRequest>()
    .HasOptional(e => e.WorkOrder)
    .WithOptionalPrincipal(e => e.JobRequest)
    .Map(m => m.MapKey("RequestNumber"));

某些操作:

  1. 添加没有WorkOrder的新JobRequest:
  2. 
    var jobRequest = new JobRequest { RequestNumber = "RN1" };
    db.JobRequests.Add(jobRequest);
    db.SaveChanges();
    

    1. 添加没有JobRequest的新WorkOrder:
    2. 
      var workOrder = new WorkOrder { WONumber = "WON1" };
      db.WorkOrders.Add(workOrder);
      db.SaveChanges();
      

      1. 添加新的JobRequest和WorkOrder(链接在一起):
      2. 
        var workOrder = new WorkOrder { WONumber = "WON2" };
        var jobRequest = new JobRequest { RequestNumber = "RN2" };
        workOrder.JobRequest = jobRequest;
        db.WorkOrders.Add(workOrder);
        db.SaveChanges();
        

        或者

        
        var workOrder = new WorkOrder { WONumber = "WON3" };
        var jobRequest = new JobRequest { RequestNumber = "RN3" };
        jobRequest.WorkOrder = workOrder;
        db.JobRequests.Add(jobRequest);
        db.SaveChanges();
        

        1. 将现有WorkOrder与现有JobRequest相关联:
        2. 
          var workOrder = db.WorkOrders.Include(e => e.JobRequest).First(e => e.WONumber == "WON1");
          var jobRequest = db.JobRequests.Include(e => e.WorkOrder).First(e => e.RequestNumber == "RN1");
          workOrder.JobRequest = jobRequest;
          db.SaveChanges();
          

          或者

          
          var workOrder = db.WorkOrders.Include(e => e.JobRequest).First(e => e.WONumber == "WON1");
          var jobRequest = db.JobRequests.Include(e => e.WorkOrder).First(e => e.RequestNumber == "RN1");
          jobRequest.WorkOrder = workOrder;
          db.SaveChanges();
          

          1. 取消关联现有的WorkOrder和JobRequest:
          2. 
            var jobRequest = db.JobRequests.Include(e => e.WorkOrder).First(e => e.RequestNumber == "RN2");
            jobRequest.WorkOrder = null;
            db.SaveChanges();
            

            or alternatively
            

            
            var workOrder = db.WorkOrders.Include(e => e.JobRequest).First(e => e.WONumber == "WON3");
            workOrder.JobRequest = null;
            db.SaveChanges();
            

            所有这些操作都按预期工作,并通过导航属性间接管理/持久隐藏(阴影)WorkOrder.RequestNumber属性。

            请注意,对断开连接的实体的操作需要特殊处理。如果您在正确实现断开连接的实体修改时遇到问题,可以创建另一个帖子并提供具体细节。