繁体   English   中英

EF6为可为空的外键生成空子实体

[英]EF6 generating empty child entity for nullable foreign key

在过去的几天里,我一直在努力解决这个问题。 我有一个Web应用程序,它与WebAPI API通信,以检索和更新由“Entity Framework Reverse POCO CodeFirst Generator”visual studio扩展创建和维护的实体。 他们似乎都生成实体和DbContext就好了。 但问题出在这里:Web客户端对API方法进行ajax调用,返回“Patient”实体。 该患者实体具有几个可以为空的外键,即LanguageId和PharmacyId。 现在,当存储库检索到患者时,它在服务器上看起来很好 错误屏幕截图1 LanguageId和PharmacyId按预期为空。 Patient的Navigation属性,即luLanguage和Pharmacy也正确地设置为null。 客户端收到的json对象此时也很好看 错误屏幕截图2 外键ID和导航属性都为null。 客户端对患者对象执行一些可选编辑,并将对象POST回服务器。 就在进行POST ajax调用之前,Patient json对象仍然看起来正常 错误屏幕截图3 外键和导航属性为null。 但是,只要WebAPI方法接收到该对象,奇怪的是,语言和药房导航属性都是空的 错误屏幕截图4 与外键对应的主键是INT,它们用0初始化。这使得DbContext在尝试更新它时会发疯,因为Language的外键和Language导航对象中的主键不匹配。 一个为null,另一个为0(零)。 我尝试了很多不同的测试,但无论我如何剪切它,我都会回到同样的问题。

这是Entity模型构建器配置代码。

public PatientConfiguration(string schema)
    {
        ToTable("Patient", schema);
        HasKey(x => x.Id);

        Property(x => x.Id).HasColumnName(@"ID").IsRequired().HasColumnType("bigint").HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);
        Property(x => x.LastName).HasColumnName(@"LastName").IsOptional().IsUnicode(false).HasColumnType("varchar").HasMaxLength(50);
        Property(x => x.FirstName).HasColumnName(@"FirstName").IsOptional().IsUnicode(false).HasColumnType("varchar").HasMaxLength(50);
        Property(x => x.MiddleName).HasColumnName(@"MiddleName").IsOptional().IsUnicode(false).HasColumnType("varchar").HasMaxLength(30);
        Property(x => x.Gender).HasColumnName(@"Gender").IsOptional().IsUnicode(false).HasColumnType("varchar").HasMaxLength(18);
        Property(x => x.Dob).HasColumnName(@"DOB").IsRequired().HasColumnType("datetime");
        Property(x => x.SocialSecurity).HasColumnName(@"SocialSecurity").IsOptional().HasColumnType("varbinary");
        Property(x => x.LastFourSsn).HasColumnName(@"LastFourSSN").IsOptional().HasColumnType("int");
        Property(x => x.PharmacyId).HasColumnName(@"PharmacyID").IsOptional().HasColumnType("bigint");
        Property(x => x.InUseById).HasColumnName(@"InUseByID").IsOptional().HasColumnType("bigint");
        Property(x => x.LanguageId).HasColumnName(@"LanguageID").IsOptional().HasColumnType("int");
        Property(x => x.Status).HasColumnName(@"Status").IsOptional().IsUnicode(false).HasColumnType("varchar").HasMaxLength(10);
        Property(x => x.IsInactive).HasColumnName(@"IsInactive").IsRequired().HasColumnType("bit");
        Property(x => x.CreatedById).HasColumnName(@"CreatedByID").IsRequired().HasColumnType("bigint");
        Property(x => x.CreatedDate).HasColumnName(@"CreatedDate").IsRequired().HasColumnType("datetime");
        Property(x => x.UpdatedById).HasColumnName(@"UpdatedByID").IsRequired().HasColumnType("bigint");
        Property(x => x.UpdatedDate).HasColumnName(@"UpdatedDate").IsRequired().HasColumnType("datetime");
        Property(x => x.MigratedBy).HasColumnName(@"MigratedBy").IsOptional().IsUnicode(false).HasColumnType("varchar").HasMaxLength(10);
        Property(x => x.TimeStamped).HasColumnName(@"TimeStamped").IsRequired().IsFixedLength().HasColumnType("timestamp").HasMaxLength(8).IsRowVersion().HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Computed);

        // Foreign keys
        HasOptional(a => a.LuLanguage).WithMany(b => b.Patients).HasForeignKey(c => c.LanguageId).WillCascadeOnDelete(false); // FK_Patient_luLanguage
        HasOptional(a => a.Pharmacy).WithMany(b => b.Patients).HasForeignKey(c => c.PharmacyId).WillCascadeOnDelete(false); // FK_Pharmacy_Patient
        InitializePartial();
    }

这是生成的患者实体

public partial class Patient : EntityBase
{
    //[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; } // ID (Primary key)
    public string LastName { get; set; } // LastName (length: 50)
    public string FirstName { get; set; } // FirstName (length: 50)
    public string MiddleName { get; set; } // MiddleName (length: 30)
    public string Gender { get; set; } // Gender (length: 18)
    public System.DateTime Dob { get; set; } // DOB
    public byte[] SocialSecurity { get; set; } // SocialSecurity
    public int? LastFourSsn { get; set; } // LastFourSSN
    public long? PharmacyId { get; set; } // PharmacyID
    public long? InUseById { get; set; } // InUseByID
    public int? LanguageId { get; set; } // LanguageID
    public string Status { get; set; } // Status (length: 10)
    public bool IsInactive { get; set; } // IsInactive
    public long CreatedById { get; set; } // CreatedByID
    public System.DateTime CreatedDate { get; set; } // CreatedDate
    public long UpdatedById { get; set; } // UpdatedByID
    public System.DateTime UpdatedDate { get; set; } // UpdatedDate
    public string MigratedBy { get; set; } // MigratedBy (length: 10)
    public byte[] TimeStamped { get; private set; } // TimeStamped (length: 8)

    // Reverse navigation
    public virtual System.Collections.Generic.ICollection<AuditPatientChange> AuditPatientChanges { get; set; } // auditPatientChange.R_88
    public virtual System.Collections.Generic.ICollection<PatientAddress> PatientAddresses { get; set; } // PatientAddress.FK_PatientAddress_Patient
    public virtual System.Collections.Generic.ICollection<PatientCallTracking> PatientCallTrackings { get; set; } // PatientCallTracking.R_74
    public virtual System.Collections.Generic.ICollection<PatientContact> PatientContacts { get; set; } // PatientContact.FK_PatientContact_Patient
    public virtual System.Collections.Generic.ICollection<PatientCreditCard> PatientCreditCards { get; set; } // PatientCreditCard.R_59
    public virtual System.Collections.Generic.ICollection<PatientDiseaseState> PatientDiseaseStates { get; set; } // PatientDiseaseState.R_65
    public virtual System.Collections.Generic.ICollection<PatientIcd10> PatientIcd10 { get; set; } // PatientICD10.R_63
    public virtual System.Collections.Generic.ICollection<PatientMedicalHistory> PatientMedicalHistories { get; set; } // PatientMedicalHistory.R_60
    public virtual System.Collections.Generic.ICollection<PatientNoteAndComment> PatientNoteAndComments { get; set; } // PatientNoteAndComment.R_73
    public virtual System.Collections.Generic.ICollection<PatientPayment> PatientPayments { get; set; } // PatientPayment.R_56
    public virtual System.Collections.Generic.ICollection<PatientPlanPolicy> PatientPlanPolicies { get; set; } // PatientPlanPolicy.R_90
    public virtual System.Collections.Generic.ICollection<PatientReferral> PatientReferrals { get; set; } // PatientReferral.FK_PatientReferral_Patient
    public virtual System.Collections.Generic.ICollection<PatientShareOfCost> PatientShareOfCosts { get; set; } // PatientShareOfCost.R_62
    public virtual System.Collections.Generic.ICollection<Rx> Rxes { get; set; } // Rx.FK_Rx_Patient

    // Foreign keys
    public virtual LuLanguage LuLanguage { get; set; } // FK_Patient_luLanguage
    public virtual Pharmacy Pharmacy { get; set; } // FK_Pharmacy_Patient

    public Patient()
    {
        IsInactive = false;
        CreatedById = 0;
        UpdatedById = 0;
        AuditPatientChanges = new System.Collections.Generic.List<AuditPatientChange>();
        PatientAddresses = new System.Collections.Generic.List<PatientAddress>();
        PatientCallTrackings = new System.Collections.Generic.List<PatientCallTracking>();
        PatientContacts = new System.Collections.Generic.List<PatientContact>();
        PatientCreditCards = new System.Collections.Generic.List<PatientCreditCard>();
        PatientDiseaseStates = new System.Collections.Generic.List<PatientDiseaseState>();
        PatientIcd10 = new System.Collections.Generic.List<PatientIcd10>();
        PatientMedicalHistories = new System.Collections.Generic.List<PatientMedicalHistory>();
        PatientNoteAndComments = new System.Collections.Generic.List<PatientNoteAndComment>();
        PatientPayments = new System.Collections.Generic.List<PatientPayment>();
        PatientPlanPolicies = new System.Collections.Generic.List<PatientPlanPolicy>();
        PatientReferrals = new System.Collections.Generic.List<PatientReferral>();
        PatientShareOfCosts = new System.Collections.Generic.List<PatientShareOfCost>();
        Rxes = new System.Collections.Generic.List<Rx>();
        InitializePartial();
    }

    partial void InitializePartial();
}

这是客户端javascript代码来测试这个问题:

function testx1(){

var patient;

$.ajax({
    type: 'GET',
    url: "/api/patient/patient/61143",
    success: function (result) {
        patient = result;
        testx2(patient);
    },
    error: function (xhr, options, error) {
        debugger;
        alert(error);
    }
});
}

function testx2(patient) {
    patient.LastFourSsn = 5555;
    patient.ObjectStateEnum = 2;
    var x = "adsf";
    $.ajax({
        type: 'POST',
        url: "/api/patient/patient",
        data: patient,
        dataType: "json",
        success: function (result) {
        },
        error: function (xhr, options, error) {
        }
     });
}

我的WebAPI代码:

        [Route("patient/{id}")]
    [HttpGet]
    public async Task<IHttpActionResult> GetPatientByIdAsync( long id )
    {
        try
        {
            var patient = await patientService.GetPatientByIdAsync( id );
            if ( patient == null )
                return NotFound();
            return Ok( patient );
        }
        catch ( Exception ex )
        {
            return InternalServerError();
        }
    }

    [Route("patient")]
    [HttpPost]
    public async Task<IHttpActionResult> SavePatient( Patient patient )
    {
        try
        {
            //if ( patient.LanguageId == null && patient.LuLanguage?.Id == 0 )
            //  patient.LuLanguage = null;
            //if ( patient.PharmacyId == null && patient.Pharmacy?.Id == 0 )
            //  patient.Pharmacy = null;
            IOperationStatus result = await patientService.UpdateAndSavePatientAsync(patient);
            if ( !result.Success )
                return InternalServerError( new Exception( result.Message ) );
            else
                return Ok();
        }
        catch ( Exception ex)
        {
            return InternalServerError(ex);
        }
    }
}

这是我的Json序列化程序设置:

    public class BrowserJsonFormatter : JsonMediaTypeFormatter
{
    public BrowserJsonFormatter()
    {
        this.SupportedMediaTypes.Add( new MediaTypeHeaderValue( "text/html" ) );
        this.SerializerSettings.Formatting = Formatting.Indented;
    }

    public override void SetDefaultContentHeaders( Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType )
    {
        base.SetDefaultContentHeaders( type, headers, mediaType );
        headers.ContentType = new MediaTypeHeaderValue( "application/json" );
    }
}

我相信您的问题与序列化对象的方式有关。

要确认这一点,请手动将Language和LanguageLu属性添加到POST。

function testx2(patient) {
patient.LastFourSsn = 5555;
patient.ObjectStateEnum = 2;
patient.LuLanguage = null;
patient.Language = null;
var x = "adsf";
$.ajax({
    type: 'POST',
    url: "/api/patient/patient",
    data: patient,
    dataType: "json",
    success: function (result) {
    },
    error: function (xhr, options, error) {
    }
 });

}

如果这样可行,那么我们可以相当确信患者对象的序列化存在问题,您应该发布您正在使用的JSON序列化程序的代码。

另外,我会进一步研究流畅的API语法。

我不得不对我的问题进行一些改动才能解决问题。 首先,我必须在我的json对象上做一个JSON.stringify,该对象即将被POST回服务器进行更新,同时在ajax帖子中特别提到“contentType:'application / json'”。 其次,我不得不使用内置在ADO.NET实体数据模型扩展中的VS来生成我的DbContext,而不是使用实体框架反向POCO生成器。 随着这些变化,事情开始奏效。 我确信如果深入研究这两个工具生成的dbContext代码,我可能会发现我的时间戳(rowversion)列未被我的WebAPI方法正确接收的原因。 但由于我处于紧张状态,我不得不推迟调查另一天。 它现在起作用,这一切都很重要,至少目前如此。 谢谢所有人试图帮助。

编辑:以防其他人遇到同样的问题,这是我在试图解决这个问题的两个痛苦的日子后发现的。 事实证明,“实体框架反向POCO生成器”使用{get;创建了rowversion属性。 私人集合},这是正确的。 但是当WebAPI方法收到POST请求时,该进程可能无法从json生成实体类,并使用该值设置timestamp列。 所以,我编辑了.tt文件,让timestamp列有公共get和set {get; set;}。 这解决了我所有的问题。 我仍然喜欢rowversion(timestamp)列的私有setter并以某种方式设置值。 但是由于时间的紧迫,我只会满足于这个解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM