在MVC3 Razor中使用LinQ到Sql将Customer.customerID输入到Advert.cutomerI

本文关键字:Customer customerID 输入 cutomerI Advert Sql Razor LinQ MVC3 | 更新日期: 2023-09-27 18:28:30

在这太久了;试图用外键填充记录中的字段,这取决于登录的用户

下面显示的是一个查看包,它在下拉列表中显示了客户的名字,用户必须选择。然后,它会在创建记录时将CustomerID放入记录中。这种方法是不切实际的

ViewBag.CustomerID = new SelectList(db.Customers, "CustomerID", "FName");

以下是通过查找CustomerID,然后将CustomerID输入到表单上的隐藏字段来自动输入外键的尝试。

   public ActionResult Create()
    {
        var CusID = from c in db.Customers
            where c.UserName == "User.Identity.Name"
            select c.CustomerID;
    return View(new CarAdvert { UserName = @User.Identity.Name, CustomerID = CusID });
    }

错误:无法隐式转换类型system.linq.Iqueryable&lt-int->到int

采取的方法(这是正确的吗!-欢迎任何关于这个主题的建议)

如需更多信息,请询问。

在MVC3 Razor中使用LinQ到Sql将Customer.customerID输入到Advert.cutomerI

关于错误:

var CusID = (from c in db.Customers
        where c.UserName == User.Identity.Name
        select c.CustomerID).Single();

你可以/应该使用.First,.FirstOrDefault,…而不是.Single,这取决于你的要求。