2021-04-07

ValueObject as Entity ID, EntityTypeConfiguration Sample

問題:https://stackoverflow.com/questions/53328201/ef-core-non-primitive-type-value-object-as-primary-key 參考來源:https://github.com/dotnet/efcore/issues/13669

public class User
    {
        public UserId Id { get; set; }
        public Credentials Credentials { get; set; }
    }

    public class UserId
    {
        private UserId()
        {

        }

        private UserId(long id)
        {
            Id = id;
        }

        public long Id { get; private set; }

        public static implicit operator long(UserId beaconId)
        {
            return beaconId.Id;
        }

        public static implicit operator UserId(long id)
        {
            return new UserId(id);
        }
        public override bool Equals(object obj)
        {
            if (obj == null)
            {
                return false;
            }

            var userId = (UserId) obj;
            return this.Id == userId.Id;
        }

        public override int GetHashCode()
        {
            return Id.GetHashCode();
        }
    }

public class TestDbContext: DbContext
    {
        public TestDbContext(DbContextOptions options): base(options)
        {

        }

        public DbSet<user> Users { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {

           var userModelBuilder = modelBuilder.Entity<user>();

            userModelBuilder.Property(x =&gt; x.Id).HasConversion(x =&gt; x.Id, value =&gt; new UserId(value)).HasColumnName("Id").IsRequired();

            userModelBuilder.OwnsOne(x =&gt; x.Credentials, c =&gt;
            {
                c.Property(x =&gt; x.Email);
                c.Property(x =&gt; x.Password);
            });
        }
    }

沒有留言:

adsense