【问题标题】:Issue inserting rows when using linq and Entity Framework使用 linq 和实体框架时插入行的问题
【发布时间】:2018-03-10 11:45:59
【问题描述】:

我对使用 Linq 和 Entity Framework 还很陌生,但我现在正尝试将行插入 SQL Server 数据库(更新行工作正常),但我无法找到以下错误的根本原因:

CS1503 参数 1:无法从“PurdisHeatingSolutions.NewCustomer”转换为“PurdisHeatingSolutions.Customer”

我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PurdisHeatingSolutions
{
    public partial class NewCustomer : System.Web.UI.Page
    {
        protected void Back_Click(object sender, EventArgs e)
        {
             Response.Redirect("~/Customers");
        }

        protected void CreateCustomerData_Click(object sender, EventArgs e)
        {
            using (var context = new PurdisHeatingSolutions.PHSContext())
            {
                Guid guid = new Guid();

                NewCustomer cust = new NewCustomer
                                       {   
                                           CustomerId = guid,
                                           CustomerName = txtCustomerName.Text.Trim(),
                                           CustomerAddress = txtCustomerAddress.Text.Trim(),
                                           ContactNumber = txtCustomerNumber.Text.Trim(),
                                           ContactEmail = txtCustomerEmail.Text.Trim()
                                      };

                txtCustomerAddress.Text = cust.CustomerName;

                context.Customers.Add(cust);
            }
        }
    }

    public partial class NewCustomer
    {
        public NewCustomer() { }

        public NewCustomer(Guid customerId, string customerName, string customerAddress, string customerContact, string customerEmail)
        {
             CustomerId = customerId;
             CustomerName = customerName;
             CustomerAddress = customerAddress;
             ContactNumber = customerContact;
             ContactEmail = customerEmail;
        }

        public Guid CustomerId { get; set; }
        public string CustomerName { get; set; }
        public string CustomerAddress { get; set; }
        public string ContactNumber { get; set; }
        public string ContactEmail { get; set; }
    }
}

线上出现错误

context.Customers.Add(cust); 

带有反对对象 cust 的论据。

我已检查对象项直接匹配上下文 Customers,但无法弄清楚我收到此问题的原因。

有人知道为什么吗?

【问题讨论】:

  • 错误信息告诉你。 Customers DbSet 适用于类型 Customer 而不是 NewCustomer
  • 非常感谢,我似乎误解了这部分的工作原理,现在对我来说很有意义。

标签: c# asp.net linq entity-framework-6


【解决方案1】:

NewCustomer 类是 System.Web.UI.Page 派生类,而您想创建 Customer 模型类对象并将它们添加到您的上下文中。您不应该通过将这两个类设为局部来混合这两个类 - Customer 模型应该是一个轻量级的纯 C# 类,只有属性,没有逻辑。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-13
    • 1970-01-01
    • 2018-01-19
    相关资源
    最近更新 更多