添加多条记录MVC时出错

时间:2014-06-06 10:40:57

标签: c# asp.net-mvc entity-framework

我试图将多个文本框值添加到数据库中,它只处理单个文本框行,但现在可以在我添加多行文本框时工作。我分享到目前为止我所做的事情。

行动方法:

public async Task<ActionResult> Create(FormCollection values)
{
    var customer = new Customer();
    var model = new TicketViewModel();
    TryUpdateModel(model.TicketDetail);

    try
    {
        foreach (var ticket in model.Tickets)
        {
            ticket.Date = DateTime.Now;
            ticket.ProcessId = DateTime.Now.Ticks.ToString().Substring(12, 6);
            ticket.CreationMethod = "Manual";
            ticket.isCustomer = User.IsInRole("Customer") ? true : false;
            ticket.Total = 0;
            ticket.Email = model.TicketDetail.Ticket.Email;

            customer.City = "Not Specified";
            customer.Country = "Not SPecified";
            customer.Image = "~/Images/nopic.jpg";
            customer.Password = System.Web.Security.Membership.GeneratePassword(11, 3);
            customer.IsActive = true;
            customer.CreationMethod = "Manual";
            customer.DateAdded = DateTime.Now;
            customer.Email = ticket.Email;
            customer.FirstMidName = string.IsNullOrEmpty(ticket.FullName) ? "Not Specified" : ticket.FullName;
            customer.LastName = "Not Specified";
            customer.Salutation = "Not Specified";
            customer.UserName = DateTime.Now.Ticks.ToString().Substring(3, 9);

            //ticket detail
            var abcd = values["abcd"].ToString();
            var getID = await db.Parts.Where(c => c.PartNumber == abcd)
                                      .FirstOrDefaultAsync();

            model.TicketDetail.GenericOrderId = ticket.GenericOrderId;
            model.TicketDetail.PersonID = customer.PersonID;
            model.TicketDetail.Status = "New";
            model.TicketDetail.PartId = getID.PartId;
            model.TicketDetail.Ticket.Date = DateTime.Now;
        }

        try
        {
            //   db.Tickets.Add(ticket);
            db.Customers.Add(customer);
            db.TicketDetails.Add(model.TicketDetail);
        }
        catch (Exception ex)
        {
            ViewBag.PartId = new SelectList(db.Parts.Take(5), "PartId", "Name");
            ModelState.AddModelError("", string.Format(ex.Message + "\n" + ex.InnerException));

            return View(model.TicketDetail);
        }

        // Save all changes
        await db.SaveChangesAsync();

        return RedirectToAction("Index");
    }
    catch(Exception ex)
    {

        ModelState.AddModelError("", String.Format(ex.Message + "\n" + ex.InnerException));
        //Invalid - redisplay with errors
        return View(model.TicketDetail);
    }
}

视图模型:

public class TicketViewModel
{
    public TicketViewModel()
    {
        TicketDetails = new List<TicketDetail>();
        TicketDetail = new TicketDetail();
        Ticket = new Ticket();
        Tickets = new List<Ticket>();
    }
    public virtual Ticket Ticket { get; set; }
    public virtual IEnumerable<Ticket> Tickets { get; set; }

    public virtual TicketDetail TicketDetail { get; set; }
    public virtual IEnumerable<TicketDetail> TicketDetails { get; set; }
}

它也在这个&#34; TryUpdateModel(model.TicketDetail);&#34;错误是值不能为空,请指导我我被困在这里我搜索了互联网,但无法找到任何合适的解决方案。我想添加多条记录

1 个答案:

答案 0 :(得分:0)

首先必须实例化TicketViewModel类的所有属性。

要添加多个记录(多个Insert),您可以使用StringBuilder并将insert语句附加到它。然后,您需要在数据库上执行一个大查询字符串。

如果使用值,这也是一种有效的方式:

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

加载要直接从文件插入的数据的速度更快。

修改 (无缘无故投票后) 因为有些人表现得像他们所知道的那样:

在处理数据库访问时,SQL注入确实是一个严重的问题。这根本不是什么秘密。一种防止SQL查询被“劫持”的常用技术。您只需使用SQLCommand.Parameters属性,该属性用于将每个值单独映射到语句,以便以这种方式将查询语句与数据(值)分开。现在不可能在不破坏它们的情况下注入或操纵语句。服务器端验证是获得最大安全性以及转义特殊输入字符和避免使用没有或没有限制的特权的标准。

这不是错误的答案。