繁体   English   中英

如何使用继承将字段添加到.NET Core 2.0中的aspNetUser表

[英]How to add fields to the aspNetUser table in .NET Core 2.0 using the inheritance

我使用aspNetUser表存储系统的用户,因此我需要知道哪个国家和城市属于这些用户,为此,我添加了以下模型城市和国家

public class Country : IEntity
    {
        public int Id { get; set; }

        [Required]
        [Display(Name = "Country")]
        [MaxLength(50, ErrorMessage = "The field {0} only can contain {1} characters length.")]
        public string Name { get; set; }

        public ICollection<City> Cities { get; set; }

        [Display(Name = "# Cities")]
        public int NumberCities { get { return this.Cities == null ? 0 : this.Cities.Count; } }
    }

public class City : IEntity
    {
        public int Id { get; set; }

        [Required]
        [Display(Name = "Ciudad")]
        [MaxLength(50, ErrorMessage = "el campo {0} solo puede contener {1} caracteres de largo.")]
        public string Name { get; set; }
    }

我添加了它从IdentityUser,CityId字段和City对象继承的User类,目的是将这些字段引入我的aspNetUser表

数据库

 public class User : IdentityUser
    {
        [Display(Name = "Nombre")]
        [MaxLength(50, ErrorMessage = "el campo {0} solo debe contener {1} caracteres de largo.")]
        public string Nombre { get; set; }

        [Display(Name = "Apellido")]
        [MaxLength(50, ErrorMessage = "el campo {0} solo debe contener {1} caracteres de largo.")]
        public string Apellido { get; set; }

        [Display(Name = "Dirección")]
        [MaxLength(100, ErrorMessage = "el campo {0} solo debe contener {1} caracteres de largo.")]
        public string Address { get; set; }

        public int CityId { get; set; }

        public City City { get; set; }

    }

问题出在我的类SeaderDB.cs(种子数据库)上,每次我删除它来执行迁移时,它都会填充数据库,这正是我的程序崩溃的地方! 组装User类并将其插入数据库时

我的seader.cs类验证是否有用户admin ....如果没有,它将创建它,但是它是在将用户对象归类时进行的

错误

SeedDB.CS:

 public async Task SeedAsync()
        {
            await this.context.Database.EnsureCreatedAsync();

            await userHelper.CheckRoleAsync("Dios");
            await userHelper.CheckRoleAsync("Admin");
            await userHelper.CheckRoleAsync("User");

            var user = await userHelper.GetUserByEmailAsync("coambiado@ing.ucsc.cl");
            if (user == null)
            {
                try
                {
                    user = new User
                    {
                        Nombre = "Cristofher",
                        Apellido = "Ambiado",
                        Email = "coambiado@ing.ucsc.cl",
                        UserName = "coambiado@ing.ucsc.cl",
                        PhoneNumber = "+56958987975",
                        EmailConfirmed = true,
                        Address = "Calle Luna Calle Sol",
                        CityId = context.Countries.FirstOrDefault().Cities.FirstOrDefault().Id,
                        City = context.Countries.FirstOrDefault().Cities.FirstOrDefault()
                    };
                }
                catch (Exception error)
                {

                }       

                var result = await userHelper.AddUserAsync(user, "fytitosk8");              
                if (result != IdentityResult.Success)
                {
                    throw new InvalidOperationException("No se pudo crear el usuario"); 
                }
                await userHelper.AddUserToRoleAsync(user, "Dios");
            }


            var isInRole = await userHelper.IsUserInRoleAsync(user, "Dios");
            if (!isInRole)
            {
                await userHelper.AddUserToRoleAsync(user, "Dios");
            }


            //AGREGAR PRODUCTOS
            if (!this.context.Productos.Any())
            {
                this.AddProductos("COMBO 1 + JUGO CITRICO",  user);
                this.AddProductos("ENSALADA CESAR + JUGO CITRICO", user);
                this.AddProductos("MENU VEGAN 1 + POSTRE",  user);
                this.AddProductos("MENU VEGAN 2 + POSTRE", user);

                await this.context.SaveChangesAsync();
            }

            //AGREGAR PAISES
            if (!this.context.Countries.Any())
            {
                var cities = new List<City>();

                cities.Add(new City { Name = "Concepción" });
                cities.Add(new City { Name = "Santiago" });
                cities.Add(new City { Name = "Iquique" });
                cities.Add(new City { Name = "Valdivia" });

                this.context.Countries.Add(new Country
                {
                    Cities = cities,
                    Name = "Chile"
                });

                await this.context.SaveChangesAsync();
            }

        }

我可以使用lamdas表达式来询问CityId的值吗? 我的代码怎么了? 我所做的这些变化好吗? Seader正在创建国家和城市,但无法在Linq的指导下获得它们……对我有帮助吗?

要添加用户,最好像其他字段一样使用默认值。 代替这些代码行;

CityId = context.Countries.FirstOrDefault().Cities.FirstOrDefault().Id,
                    City = context.Countries.FirstOrDefault().Cities.FirstOrDefault()


例如,您可以使用它;

user = new User
                {
                    Nombre = "Cristofher",
                    Apellido = "Ambiado",
                    Email = "coambiado@ing.ucsc.cl",
                    UserName = "coambiado@ing.ucsc.cl",
                    PhoneNumber = "+56958987975",
                    EmailConfirmed = true,
                    Address = "Calle Luna Calle Sol",
                    CityId = 1,
                    City = new City { Id =1, Name = "Concepción" } 
                };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM