c# - 在 MVC3 Razor 中使用 LinQ to Sql 将 Customer.customerID 输入 Advert.cutomerID

标签 c# linq asp.net-mvc-3

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

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

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

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

   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 <-int-> 隐式转换为 int

所采取的方法(这是正确的吗?-欢迎就此主题提出任何建议)

需要更多信息请询问。

最佳答案

关于错误:

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

代替 .Single,您可以/应该使用 .First、.FirstOrDefault、...,具体取决于您的要求。

关于c# - 在 MVC3 Razor 中使用 LinQ to Sql 将 Customer.customerID 输入 Advert.cutomerID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9815175/

相关文章:

c# - 如何在 Silverlight 中找到父级的每个元素

javascript - jqGrid userData 在 View 中显示值(asp.net mvc3)

c# - 在数据注释的 ErrorMessage 属性中使用 html

c# - 尽管有一个方法,但没有找到合适的方法来覆盖 c#?

c# - 如何使用方法 CreatedAtRoute() 响应发布请求

c# - LINQ 按空列排序,其中顺序是升序的,空值应该排在最后

asp.net-mvc - 没有布局的 Razor View

C# WebApi Odata - EF 不过滤

c# - 使用 RIA 服务在 Silverlight 中进行数据绑定(bind)

c# - StackOverflowException 对嵌套数据使用 Linq(Kit)