gpt4 book ai didi

c# - 使用 EntityTypeConfiguration 时的抽象域模型基类

转载 作者:太空狗 更新时间:2023-10-29 21:09:42 25 4
gpt4 key购买 nike

获取 Base 对象属性的集中映射是否有一些技巧?使用 EntityTypeConfiguration 时是否有一些抽象类的简单模式。
非常感谢任何提示。我无法声明一个类

Public class BaseEntityConfig<T> : EntityTypeConfiguration<T>

类似的问题,我无法得到工作的答案 How to create and use a generic class EntityTypeConfiguration<TEntity>Dynamic way to Generate EntityTypeConfiguration : The type 'TResult' must be a non-nullable value type

public  abstract class BosBaseObject
{
public virtual Guid Id { set; get; }
public virtual string ExternalKey { set; get; }
public byte[] RowVersion { get; set; }
}
public class News : BosBaseObject
{
public String Heading { set; get; }
}


public class NewsMap : EntityTypeConfiguration<News>
{
public NewsMap()
{
//Base Object Common Mappings
// How can we use a central mapping for all Base Abstract properties


}
}
// Something like this but very open to any suggestion....
public class BosBaseEntityConfig<T> : EntityTypeConfiguration<T>
{
public void BaseObjectMap( )
{
// Primary Key
this.HasKey(t => t.Id);

// Properties
this.Property(t => t.Id).HasDatabaseGeneratedOption(databaseGeneratedOption: DatabaseGeneratedOption.None);

this.Property(t => t.RowVersion)
.IsRequired()
.IsFixedLength()
.HasMaxLength(8)
.IsRowVersion();

//Column Mappings
this.Property(t => t.Id).HasColumnName("Id");
}
}

最佳答案

上面的答案肯定有效,尽管这可能更清晰一些,并且在 DbContext 中注册配置时具有相同的工作原理。

public abstract class BaseEntity
{
public int Id { get; set; }
}

public class Company : BaseEntity
{
public string Name { get; set; }
}

internal class BaseEntityMap<T> : EntityTypeConfiguration<T> where T : BaseEntity
{
public BaseEntityMap()
{
// Primary Key
HasKey(t => t.Id);
}
}

internal class CompanyMap : BaseEntityMap<Company>
{
public CompanyMap()
{
// Properties
Property(t => t.Name)
.IsRequired()
.HasMaxLength(256);
}
}

public class AcmeContext : DbContext
{
public DbSet<Company> Companies { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new CompanyMap());
}
}

上述解决方案是 Christian Williams 和我在一天清晨得出的......

关于c# - 使用 EntityTypeConfiguration<T> 时的抽象域模型基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13437769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com