【问题标题】:Entity framework not able to add data实体框架无法添加数据
【发布时间】:2022-10-14 01:38:57
【问题描述】:

所以我正在做一个必须使用 EF 的项目,但尝试向表中添加新数据似乎每次都失败。我不知道为什么/如何解决它。

执行的代码是:

private static void AddCustomer()
    {
        WriteAdminMenu("Add new customer");
        Console.Write("First name: ");
        ...
        WriteAdminMenu("Adding customer...");
        using (var db = new EshopContext())
        {
            db.Addresses.Add(new Address(customerStreet, customerZip, customerCity, customerCountry));
        }

    }

它给出了以下错误:

System.InvalidOperationException: 'No suitable constructor was found for entity type 'Address'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'zip' in 'Address(string street, string zip, string city, string country)'.'

上下文文件:

public class EshopContext : DbContext
{
    public DbSet<Customer>? Customer { get; set; }
    public DbSet<Address>? Addresses { get; set; }
    public DbSet<Order>? Orders { get; set; }
    public DbSet<Product>? Products { get; set; }
    public DbSet<Tag>? Tags { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
       => options.UseSqlServer("Data Source=TotallyMyIp;Initial Catalog=MyDatabaseName;Persist Security Info=True;User ID=TotalyMyUserName;Password=totallySecretPassword");
}

我的地址模型:

public int Id { get; set; }
    public string Street { get; set; }
    public string Zipcode { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
    public Address(string street, string zip, string city, string country)
    {
        Street = street;
        Zipcode = zip;
        City = city;
        Country = country;
    }

【问题讨论】:

    标签: entity-framework


    【解决方案1】:

    框架没办法知道zipZipcode是一样的。

    保持你的名字一致:

    public Address(string street, string zipcode, string city, string country)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-02
      • 2020-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多