如何更新实体记录 [英] How do I update entity record

查看:49
本文介绍了如何更新实体记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从6的列表中更新4号记录,但下面的保存更改方法是用更新覆盖我的第1条记录。我知道我哪里出错了(看到粗体)但不知道如何纠正它,有人可以告诉我吗?

I'm trying to update record number 4 from a list of 6 but my save changes method below is overwriting my 1st record with the updates instead. I know where I am going wrong(see the bold) but just not sure how to correct it, can someone please advise me?

private void btnSave_Click(object sender, EventArgs e)
{
    var contact = context.Contacts.First();
    var address = context.Address.First();    
    string[] name = txtTenant.Text.Split(' ');
    contact.FirstName = name[0].ToString();
    contact.LastName = name[1].ToString();
    address.Address1 = txtAddress.Text;                                              
    contact.ContactNumber = txtContactNum.Text;
    address.Mortgage = txtMortgage.Text;
    address.RemainingMortgage = txtRemainingMortgage.Text;
    address.Rent = txtRent.Text;
    address.Period = cboPeriod.SelectedIndex;
    address.RentArrears = txtRentArrears.Text;
    address.Rates = txtRates.Text;
    address.RatesUpToDate = chkRates.Checked;
    address.RentArrears = txtRentArrears.Text;
    address.Repairs = txtRepairs.Text;
    
    context.SaveChanges();
    SetContactsDDL(cboContactList.SelectedIndex);
}

推荐答案

这是一个实体框架101主题。我认真地建议在实体框架上拿起Julia Lerman(?)的书并通过它们进行工作。



我不知道你是如何从数据库中获取记录的,但它应该在某些字段中具有Id(主键字段)编号。使用它来使用上下文查找记录。

This is a Entity Framework 101 topic. I seriously suggest picking up the books by Julia Lerman(?) on Entity Framework and workign through them.

I have no idea how you got the record from the database, but it should have it's Id (primary key field) number in some field. Use that to lookup the record using the context.
Contact contactToUpdate = context.Contacts.Find(contactId);
...
contact.FirstName = name[0].ToString();
... blah blah blah ...


// Depending on how you're doing things, you may need to do this to
// force EF to consider the record "dirty".
context.Entry(contactToUpdate).State = EntityState.Modified;

context.SaveChanges();


这篇关于如何更新实体记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆