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

标签 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(collection);

The best overloaded method match for 'CustomerPortalMVC.Models.CustomerPortalEntities_Customer_Downloads.AddToCustomer_Downloads(CustomerPortalMVC.Models.Customer_Downloads)' has some invalid arguments

Argument '1': cannot convert from 'System.Web.Mvc.FormCollection' to '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"); 
} 

关于c# - 使用 Entity Framework 将新记录插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11109272/

相关文章:

c# - 连接数据库时出现错误

c# - EF Core 播种机制不插入数据

c# - Add-Migration 不会检测外键的更改

c# - Linq 没有返回所有需要的数据

c# - 使用反射导航到单独程序集中的页面

c# - Visual C# 从自定义目录读取字体

c# - 如何使用 XPath for HTML 获取子节点的数量?

c# - ADO.Net:在解决方案中的多个项目之间共享实体 (.edmx)

.net - 将我的思维方式从 ASP.NET 迁移到 ASP.NET MVC 时需要了解哪些关键概念 (2)?

c# - 为什么我的 MVC viewModel 为空?