簡體   English   中英

使用實體框架將新記錄插入數據庫

[英]Insert new record into database using Entity Framework

我的數據庫中有一個這樣的表:

[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”

要進行這項工作,我需要更改什么?

您需要向方法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"); 
} 

您需要創建Customer_Downloads類的實例,並將其傳遞給AddToCustomer_Downloads方法。 錯誤消息告訴您該方法的接口需要一個Customer_Downloads對象,但是您正在向其傳遞FormCollection對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM