注:“2020中國.NET開發者大會”上學習到的開發技巧, 記錄下來
1.問題
后端代碼已定義的用戶實體,如下:
public class UserEntity
{
public Guid UserId {get; set;}
public string UserName {get; set;}
public string Password {get; set;}
}
現在需求是在不改變實體類結構代碼的情況下, 對該實體新增一個Gender
字段, 如何做呢?
2.解決方案
利用
EF Core
的索引屬性;
實體上可以不定義字段;
字段數據存儲在字典中;
2.1 定義基類
public abstract class BaseEntity
{
private Dictionary<string, object> _values = new Dictionary<string, object>();
//動態創建字段
public object this[string key]
{
get
{
if(_values.TryGetValue(key, out var value))
return value;
return null;
}
set => _values[key] = value;
}
}
2.2 繼承
public class UserEntity : BaseEntity
{
public Guid UserId {get; set;}
public string UserName {get; set;}
public string Password {get; set;}
}
2.3 在DbContex中定義擴展字段
public class TestDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder. Entity<UserEntity>(entity =>
{
entity.IndexerProperty<string>("Gender")//定義"性別"字段信息
.HasMaxLength(64);
});
}
}
2.4 使用
Using(TestDbContext dbContext= new TestDbContext())
{
var userEntity = new UserEntity();
userEntity.UserName = "admin";
userEntity.Password = "123";
userEntity["Gender"] = "男";
dbContext.Set<UserEntity>().Add(userEntity);
dbContext.SaveChanges();
}