五维思考

学习要加,骄傲要减,机会要乘,懒惰要除。 http://www.5dthink.cn

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

注:“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();
}
posted on 2021-02-19 13:29  五维思考  阅读(1043)  评论(0编辑  收藏  举报

QQ群:1. 全栈码农【346906288】2. VBA/VSTO【2660245】