【问题标题】:Cannot implicitly convert type 'System.Collections.Generic.List<model1>' to 'System.Collections.Generic.List<model2>无法将类型“System.Collections.Generic.List<model1>”隐式转换为“System.Collections.Generic.List<model2>”
【发布时间】:2021-11-22 16:51:55
【问题描述】:

我在 SQL 数据库中基于以下类创建了两个表,我的第一个表是(Clients):

public string Id { get; set; } = default!;
public double? Name { get; set; } = default!;
public string? FamilyName { get; set; } = default!;
public List<Addresses> ClientAddress { get; set; } = default!;

我的第二张表是地址:

public string Id { get; set; } = default!;
public string Address { get; set; } = default!;

我在互联网上找到了这种方法!现在问题是我从 UI 获取客户端模型并想将它存储在 linq 中我应该如何做?我得到错误:

public Task<bool> StoreModel(Clients client)
{
     var listtostore = new ClientsEntity()
       {
           Name = client.Name,
           FamilyName = client.FamilyName,
           ClientAddress =client.ClientAddress//i get conversion error here
       }
}

我的客户实体是:

 [Key]
    public string Id { get; set; } = default!;
    public double? Name { get; set; } = default!;
    public string? FamilyName { get; set; } = default!;
    public List<Addresses> ClientAddress { get; set; } = default!;

【问题讨论】:

  • 请出示ClientsEntity
  • @OneCricketeer 更新了我的问题
  • 为什么你实际上有两个完全相同的类? ClientsClientsEntity?
  • 不要以复数形式命名类。以复数形式命名作为集合的属性
  • 我的猜测是客户端类 (DTO) 中的“地址”与 ClientEntity (实体) 中的“地址”是不同的类型。您的命名约定非常混乱,并且可能不太一致。在任何情况下,如果您在实体和实体旁边使用 ViewModel/DTO 时遇到麻烦,您不应该在实体和 DTO 之间混合实体引用(地址)。您的实体 DTO 的地址 DTO 很可能具有相同的类名。

标签: c# entity-framework .net-core


【解决方案1】:

ClientAddress 是一个列表

先初始化它们然后再试一次

listtostore.ClientAddress = new List<Addresses>();

foreach(var item in client.ClientAddress)
{
listtostore.ClientAddress.Add(item)
}

【讨论】:

  • 这是最好的方法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-08
  • 2019-01-03
  • 1970-01-01
  • 2020-06-16
相关资源
最近更新 更多