最后一项仅添加到db

时间:2016-07-24 21:19:32

标签: c#

我正在尝试将一些控件添加到列表中,但由于某种原因,它只将最后一个视图保存到数据库。

public List<tblPortalIandEValue> createIandERecord(Guid _userId, string fieldName, string fieldValue)
{
    List<tblPortalIandEValue> _iandevalues = new List<tblPortalIandEValue>();
    _iandevalues.Add(new tblPortalIandEValue { userId = _userId, field_name = fieldName, field_value = fieldValue });

    return _iandevalues;
}

我认为我的问题在于我的保存因为我调用此列表添加新的然后返回它认为我应该返回记录

protected void btnSave_Click(object sender, EventArgs e)
{
    List<tblPortalIandEValue> _iandevalues = new List<tblPortalIandEValue>();
    _customerId = Guid.NewGuid();
    _iandevalues=_dal.createIandERecord(_customerId , "mortagecic", mortagecic.Value.ToString());

    _iandevalues = _dal.createIandERecord(_customerId, "gascic", gascic.Value.ToString());
    _iandevalues = _dal.createIandERecord(_customerId, "electricitycic", electricitycic.Value.ToString());

    _iandevalues.ForEach(n =>_dal.portalEntities.tblPortalIandEValues.Add(n));
    _dal.portalEntities.SaveChanges();
}

1 个答案:

答案 0 :(得分:1)

您的问题出在createIandERecord方法中,因为您每次都在更新列表。将您的代码更改为:

 public tblPortalIandEValue createIandERecord(Guid _userId, string fieldName, string fieldValue)
    {
        return new tblPortalIandEValue { userId = _userId, field_name = fieldName, field_value = fieldValue });
            }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        List<tblPortalIandEValue> _iandevalues = new List<tblPortalIandEValue>();
        _customerId = Guid.NewGuid();
        _iandevalues.Add(_dal.createIandERecord(_customerId, "mortagecic", mortagecic.Value.ToString()));

        _iandevalues.Add(_dal.createIandERecord(_customerId, "gascic", gascic.Value.ToString()));
        _iandevalues.Add(_dal.createIandERecord(_customerId, "electricitycic", electricitycic.Value.ToString()));
        _iandevalues.ForEach(n => _dal.portalEntities.tblPortalIandEValues.Add(n));
        _dal.portalEntities.SaveChanges();

    }