使用Entity Framework将新记录插入数据库

时间:2012-06-19 20:54:14

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

我的数据库中有一个表格如下:

[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(集合)行上;

  

'CustomerPortalMVC.Models.CustomerPortalEntities_Customer_Downloads.AddToCustomer_Downloads(CustomerPortalMVC.Models.Customer_Downloads)'的最佳重载方法匹配   有一些无效的论点

     

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

我需要做些什么来改变这项工作?

2 个答案:

答案 0 :(得分:4)

您需要向方法CustomerPortalMVC.Models.Customer_Downloads提供AddToCustomer_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"); 
} 

答案 1 :(得分:1)

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