C# EF Core 后端代码已定义的用户实体,如何扩展字段?

注:“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();
}
原文地址:https://www.cnblogs.com/zhaoshujie/p/14415682.html