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();
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM