简体   繁体   中英

Save Null value in SQL Server via Entity Framework

I have a table in which I need to insert Null value. Inside " FamilyTreeMember " table I have a column called " BirthMonth_Id " which is a FK to another table called BirthMonthDD . BirthMonthDD is my lookup table which I use it to generate DropDownList items.

In my current setup, I need to allow the end user to leave that field blank and save it as Null but it doesn't happen that way and instead it returns the old/same value. I don't get any error message. I can easily update the value from one thing to another. Example from February to August and ...

How can I fix this?

Model

public class FamilyTreeMember
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        [Key]
        public Guid FamilyTreeMemberId { get; set; }

        public int? BirthDay { get; set; }
        public virtual MonthDD BirthMonth { get; set; }
        public int? BirthYear { get; set; }
        public bool DOBEstimated { get; set; }       
    }

ViewModel

public class EditFamilyTreeMemberViewModel
    {
        [ScaffoldColumn(false)]
        public string CaseId { get; set; }

        [ScaffoldColumn(false)]
        public string FamilyTreeMemberId { get; set; }


        [UIHint("Day")]
        [RegularExpression(@"([0-9]+)", ErrorMessage = "The {0} must be a number.")]
        [Display(Name = "Day Of Birth")]
        public int? BirthDay { get; set; }

        [UIHint("ComboBox")]
        [AdditionalMetadata("BindTo", "months")]
        [Display(Name = "Month Of Birth")]
        public int? BirthMonth { get; set; }


        [UIHint("Year")]
        [RegularExpression(@"([0-9]+)", ErrorMessage = "The {0} must be a number.")]
        [Display(Name = "Year Of Birth")]
        public int? BirthYear { get; set; }

        [UIHint("Bool")]
        [Display(Name = "DOB Estimated")]
        public bool DOBEstimated { get; set; }
    }

Controller (Update method)

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(EditFamilyTreeMemberViewModel editfamilytreemember, Guid? ftm, Guid? cid, Guid? mid)
{
    ViewBag.ftm = ftm;
    ViewBag.cid = cid;
    ViewBag.mid = mid;

    if (ModelState.IsValid)
    {
        if (ftm == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.NotFound);
        }
        using (db)
        {
            var ftmember = await db.FamilyTreeMember.SingleOrDefaultAsync(z => z.FamilyTreeMemberId == ftm);

            ftmember.BirthDay = editfamilytreemember.BirthDay;
            ftmember.BirthMonth = await db.MonthDD.SingleOrDefaultAsync(x => x.Id == editfamilytreemember.BirthMonth);
            ftmember.BirthYear = editfamilytreemember.BirthYear;
            ftmember.DOBEstimated = editfamilytreemember.DOBEstimated;

            await db.SaveChangesAsync();
        }
        return RedirectToAction("Index", "FamilyTree", new { cid, mid });
    }
    return View();
}

The problem is that you can't break a relationship that has not been loaded before. So either Include the relationship when you query for your member:

var ftmember = await db.FamilyTreeMember.Include(x => x.BirthMonth).SingleOrDefaultAsync(z => z.FamilyTreeMemberId == ftm);

Or load this relationship before you set it to null :

db.Entry(ftmember).Reference(x => x.BirthMonth).Load();

This problem arises becase the property is null before you assign it (since the relationship hasn't been loaded), so when you assign null to it, it doesn't mark it as modified.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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