【问题标题】:Insert new record into database using Entity Framework使用实体框架将新记录插入数据库
【发布时间】:2012-06-19 20:54:13
【问题描述】:

我的数据库中有一个这样的表:

[id] [uniqueidentifier] NOT NULL,
[user_id] [uniqueidentifier] NOT NULL,
[download_type] [nvarchar](50) NOT NULL,
[download_id] [nvarchar](50) NOT NULL,
[download_date] [datetime] NOT NULL,
[user_ip_address] [nvarchar](20) NOT NULL,

id 被定义为主键。

我想在这个表中插入一条新记录。这是我无法开始工作的代码。

CustomerPortalEntities_Customer_Downloads dbcd = new CustomerPortalEntities_Customer_Downloads();

public ActionResult Download(string id)
{
    var collection = new FormCollection();
    collection.Add("user_id", Membership.GetUser().ProviderUserKey.ToString());
    collection.Add("download_type", "Car");
    collection.Add("download_id", id);
    collection.Add("download_date", DateTime.Now.ToString());
    collection.Add("user_ip_address", Request.ServerVariables["REMOTE_ADDR"]);            

    dbcd.AddToCustomer_Downloads(collection);

    return Redirect("../../Content/files/" + id + ".EXE");
}

我得到的错误是 dbcd.AddToCustomer_Downloads(collection);

“CustomerPortalMVC.Models.CustomerPortalEntities_Customer_Downloads.AddToCustomer_Downloads(CustomerPortalMVC.Models.Customer_Downloads)”的最佳重载方法匹配 有一些无效的参数

参数“1”:无法从“System.Web.Mvc.FormCollection”转换为 'CustomerPortalMVC.Models.Customer_Downloads'

我需要进行哪些更改才能完成这项工作?

【问题讨论】:

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


    【解决方案1】:

    您需要向方法AddToCustomer_Downloads 提供一个CustomerPortalMVC.Models.Customer_Downloads 类型的对象,然后在您的数据上下文中调用SaveChanges,如下所示:

    public ActionResult Download(string id) 
    { 
        var item = new CustomerPortalMVC.Models.Customer_Downloads(); 
        item.user_id = Membership.GetUser().ProviderUserKey.ToString(); 
        item.download_type = "Car"; 
        item.download_id = id; 
        item.download_date = DateTime.Now.ToString(); 
        item.user_ip_address = Request.ServerVariables["REMOTE_ADDR"];             
        dbcd.AddToCustomer_Downloads(item); 
        dbcd.SaveChanges(); 
        return Redirect("../../Content/files/" + id + ".EXE"); 
    } 
    

    【讨论】:

      【解决方案2】:

      您需要创建 Customer_Downloads 类的实例并将其传递给您的 AddToCustomer_Downloads 方法。错误消息告诉您该方法的接口需要一个 Customer_Downloads 对象,但您正在向它传递一个 FormCollection 对象。

      【讨论】:

      • 伙计,我知道这很简单,谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-04
      相关资源
      最近更新 更多