在 EF 核心中使用嵌套类

问题描述 投票:0回答:1

我使用 EF core 来操作基础并且我有类 Customer

public class Customer
{
        public Customer(string fullname, Address address)
        {
            this.Id = IdGenerator.GetId();

            this.Fullname = fullname;
            this.Address = address;
        }

        public int Id { get; }

        public string Fullname { get; set; }

        public Address Address { get; set; }
}

我有地址课

public class Address
{
        public Address(int index, string country, string city, string building, string apartment)
        {
            this.Index = index;
            this.Country = country;
            this.City = city;
            this.Building = building;
            this.Apartment = apartment;
        }

        public int Index { get; set; }

        public string Country { get; set; }

        public string City { get; set; }

        public string Building { get; set; }

        public string Apartment { get; set; }
}

当我尝试在数据库中添加客户时,出现错误

System.InvalidCastException: Unable to cast object of type 'oop_backend.Models.Address' to type 'System.String'.
   at System.ComponentModel.DataAnnotations.StringLengthAttribute.IsValid(Object value)
   at System.ComponentModel.DataAnnotations.ValidationAttribute.IsValid(Object value, ValidationContext validationContext)
   at System.ComponentModel.DataAnnotations.ValidationAttribute.GetValidationResult(Object value, ValidationContext validationContext)
   at Microsoft.AspNetCore.Mvc.DataAnnotations.DataAnnotationsModelValidator.Validate(ModelValidationContext validationContext)

我不明白我需要做什么来修复这个错误

c# entity-framework asp.net-core-mvc
1个回答
0
投票

这是您的数据库实体还是只是一个模型?如果只是一个模型,您必须将其映射到实体然后插入。

如果不是这种情况,则可能在您的上下文中缺少某些配置。 在您的上下文中,您应该同时拥有这两个实体,例如:

public DbSet<Customer> Customer { get; set; }
public DbSet<Address> Address { get; set; }
© www.soinside.com 2019 - 2024. All rights reserved.