Inheritance one-to-one or zero relationship with IdentityUser class

295 views Asked by At

This is my Classes :

 public class ApplicationUsers : IdentityUser<Guid>
    {

        [InverseProperty("ApplicationUser")]
        public virtual User User { get; set; }
        [InverseProperty("ApplicationUser")]
        public virtual WorkerTaxi WorkerTaxi { get; set; }

    }

Person Abstract Class :

    public abstract class Person
    {

        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public Guid PersonId { get; set; }
        ....
    }

User Class :

public class User:Person
    {
        ....
        [ForeignKey("PersonId")]
        [InverseProperty("User")]
        public virtual ApplicationUsers ApplicationUser { get; set; }

    }

And WorkerTaxi Class :

public class WorkerTaxi : Person
    {
        .....
        [ForeignKey("PersonId")]
        [InverseProperty("WorkerTaxi")]
        public virtual ApplicationUsers ApplicationUser { get; set; }

    }

I want to have one to one or zero relationship between ApplicationUsers.cs and User.cs and ApplicationUsers.cs and WorkerTaxi.

When I run this test, it passes without any problem :

[TestMethod]
        public async Task Verify_GetAllUser_Method()
        {
            using (var serviceScope = _serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
            {
                var userManager =
                    serviceScope.ServiceProvider.GetRequiredService<UserManager<ApplicationUsers>>();
                var id = Guid.NewGuid();
                var applicationUsersService =
                    serviceScope.ServiceProvider.GetRequiredService<IApplicationUsersRepository>();
                //--Arrange
                var user = new ApplicationUsers
                {
                    Id = id,
                    Email =
                        "X7n8N1JeD6CgecTnkdvmtH1sJZI=LY9R6hsG0Or3OSwv9nmDnQ==62ZLaR17B3BIAeQIIE57EZGlT8LwVlSEiB/ih3H1XxE=",
                    PhoneNumber = "qUqP5cyxm6YcTAhz05Hph5gvu9M=kByTpFP12CIONabzOFXQTg==fY6QbrosN2tQhXVZS82ZYg==",
                    UserName = "qUqP5cyxm6YcTAhz05Hph5gvu9M=FJZ1IeRcp4OHZzgdCwTJgQ==Jsgka2bvSbI/pzO3vbkOzg==",
                    User = new User
                    {
                        PersonId = id,
                        FirstName = "fTWDgtfCCdjrNPKhQpSYpA7NnV8=5dq1Tep3IfFLtabGzAKN0w==YA7slsTLCozHt7Mgn1pbXw==",
                        LastName = "qUqP5cyxm6YcTAhz05Hph5gvu9M=M6V+PMrCVyecbJPmE4853A==QWUrHVtr2I7ow6oDfZ/6ZQ==",
                        ProfileImage =
                            "SuGM+8hg8C3OCxpHd0Jgyu8/an4=yMfzTFs6xEp7SBxN8VvzcA==bJLLw5auqsptskn0hNXDd3nZPBIXbvaZEaQHq90IRCLkzCWflLCgi+NBBarLVdft",
                        Gender = Gender.Female
                    }
                };
                await userManager.CreateAsync(user: user);
                const int expected = 1;
                //--Actual
                var actual = applicationUsersService.GetAllUser().Count;
                //--Assert
                Assert.AreEqual(expected: expected, actual: actual);
                await userManager.DeleteAsync(user: user);
            }
        }

But when I run this test , I got this error :

[TestMethod]
        public async Task Verify_GetAllWorker_Method()
        {
            using (var serviceScope = _serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
            {
                var userManager =
                    serviceScope.ServiceProvider.GetRequiredService<UserManager<ApplicationUsers>>();
                var applicationUsersService =
                    serviceScope.ServiceProvider.GetRequiredService<IApplicationUsersRepository>();
                //--Arrange
                var id = Guid.NewGuid();


                var worker = new ApplicationUsers
                {
                    Id = id,
                    Email =
                        "X7n8N1JeD6CgecTnkdvmtH1sJZI=uRzzvxiDclXJEkm+HwZcDw==WvfCqqAJRunNYo7DGno1ESxt00+ipRxYJ5jDJYq2rSg=",
                    PhoneNumber = "qUqP5cyxm6YcTAhz05Hph5gvu9M=alh9Stp8ok1XweUNhuDmIQ==NH5G7k2lHTOxDS24SGTXUg==",
                    UserName = "qUqP5cyxm6YcTAhz05Hph5gvu9M=bLI2HWYq0LnnkzLXKLvjwQ==V+9M/G5yeXMs7J71+vSbjQ==",
                    IsDeleted = false,
                    WorkerTaxi = new WorkerTaxi
                    {
                        PersonId = id,
                        BirthDate = DateTime.Now,
                        BirthPlace = "qUqP5cyxm6YcTAhz05Hph5gvu9M=T588vuuioT1zHIz7o4GTTw==A+K+k4/rXJmOhF2hbKX5DA==",
                        DeviceNumber = "pBHfwiS9RrhpHuwP7q4VYLgLUSw=cLNp+s2+DdCXbhux17lziw==I+BLV+WUWnsnLe7GEcKokw==",
                        DocumentImage =
                            "NbGHR/RrGeFenDWNnQ7LazgoKQY=9Wv1ku4hybd64s3ouNnhVg==gmUKXu+YU5hSkTfMJxOT4v7250tSLW0pc5SoY9JLVv/lQ1hnqQyyqZXAoG5MSCH8",
                        Driver = DriverType.Taxi,
                        DriverLicenseCode =
                            "u1YSKbB4W+eqDeKgx8rlrTPW1DQ=pIMDMdWdYtOye+d8GGf/lw==fyF11Wfkvpvm2uZJwCdwFg==",
                        DriverLicenseDate = DateTime.Now,
                        FatherName = "qUqP5cyxm6YcTAhz05Hph5gvu9M=0KIKpi8TXapLLANwAc3GWQ==Bqvh93OkxhhijBuLjiOwcg==",
                        FirstName = "fTWDgtfCCdjrNPKhQpSYpA7NnV8=G63WGL6+dmkDC0ExczxZrA==ggRbM3Df4dcmtYkp7KVohw==",
                        LastName = "qUqP5cyxm6YcTAhz05Hph5gvu9M=wTKx3cxcuxy5JqJd6obNSg==SxhwZxvzUlo7EprR+bHKTg==",
                        MeliCode = "IsVVIlMUNB9bd7y7yt4mlaFH76I=4+zDBqu22x2y9swI0EvgeA==S4u4K8ayuYp+hoRFV8s3yA==",
                        MeliCartImage =
                            "xbCEQTXyjhgIYCBWGOWDNX8yAeE=5eTXYSPcp2iDRLZSLGyBmw==R1ovaeqtJVbqgmqpCmF7wyrAFRgwybGpDnTLhejwRQ6rr0GvlLNzKvKoUSyJdafu",
                        ProfileImage =
                            "0EeKhLI1OG/f880FKzQG44gjiTo=TPMcxyaaPT4GcWC/k/laFw==vFV8ADkG8qoberKI+kEXPlIBslJUcUbAaVpWX4zf23gVooVw0jkhtFDJCxKQEIyr",
                        ShenasnamehCode = "gAc7m531mVKARZseE9/OL7eickU=57mUHw4a4NdLXLXdpPeEiA==txffKzYDvOh+bODJEN++0w==",
                        ShenasnamehImage =
                            "YRgn4oJ6HKekyKf06REGbtWpgiI=p6O8EVq53kzvAZEaIQYHGQ==Wu92TrssQkLe8AwcmUdyrvVeyV/b+Btf6PnYZsi4hUa9xknRBC0WVqnUE15VEHk3",
                        TaradodCode = "0kyb/jWQsXrWikM+TPHY/O/r62Q=iSMFo/gq5lvqo7L3SdhbFg==3v8kTvaulmjXfGJ6nwBTrQ==",
                        TaxiCode = "0kyb/jWQsXrWikM+TPHY/O/r62Q=bpyuyaihQRmk0orrStzgbw==7quLu5AYu9mJZkYujeHfMg==",
                        Gender = Gender.Female
                    }
                };
                await userManager.CreateAsync(user: worker);
                const int expected = 1;
                //--Actual
                var actual = applicationUsersService.GetAllWorkerTaxi().Count;
                //--Assert
                Assert.AreEqual(expected: expected, actual: actual);
                await userManager.DeleteAsync(user: worker);
            }
        }

PS.ServiceTest.ApplicationUsersRepositoryTest.Verify_GetAllWorker_Method threw exception: System.InvalidCastException: Unable to cast object of type 'PS.Model.Models.Taxi.WorkerTaxi' to type 'PS.Model.Models.User'.

The error was occurred when await userManager.CreateAsync(user: worker) was ran.

Where is the Problem ?

How can I fix that ?

Update

I found the real problem .... when it tries to add WorkerTaxi to Person table , the discriminator is always 0 base on this code :

public enum AccountType
    {
        User = 0,
        TaxiWorker = 1
    }
  model.Entity<Person>()
                .HasDiscriminator<int>(name: "Type")
                .HasValue<WorkerTaxi>(value: Convert.ToInt32(value: AccountType.TaxiWorker))
                .HasValue<User>(value: Convert.ToInt32(value: AccountType.User));

How can i fix that ?

should the code determine the discriminator or not ?

0

There are 0 answers