C# 检查所有表中相同列的值[实体框架]
我在数据库中有100多个表,其中60多个表包含名为C# 检查所有表中相同列的值[实体框架],c#,entity-framework,linq-to-entities,C#,Entity Framework,Linq To Entities,我在数据库中有100多个表,其中60多个表包含名为ShortCode nvarchar(12)的列,这些列表示该记录的全局唯一代码 现在有没有办法找到ShortCode值,例如AST\u SHIP\u FIRE出现在数据库的任何表中 注意:快捷码由用户定义 目前我尝试下面的代码,它的工作,但我必须为所有表的代码 if (entities.Table1.Any(x => x.ShortCode.Trim().ToLower() == a.ShortCode.Trim().ToLower()
ShortCode nvarchar(12)
的列,这些列表示该记录的全局唯一代码
现在有没有办法找到ShortCode
值,例如AST\u SHIP\u FIRE
出现在数据库的任何表中
注意:快捷码
由用户定义
目前我尝试下面的代码,它的工作,但我必须为所有表的代码
if (entities.Table1.Any(x => x.ShortCode.Trim().ToLower() == a.ShortCode.Trim().ToLower())
{return false;}
else if(entities.Table2.Any(x => x.ShortCode.Trim().ToLower() == a.ShortCode.Trim().ToLower()))
{return false;}
else if( entities.Talble3.Any(x => x.ShortCode.Trim().ToLower() == a.ShortCode.Trim().ToLower()))
{return false;}
.
.
.
else
{
//insert code
}
我认为可能有更有效的方法。好的,也许不是很简单,但让我们做吧 首先,为
ShortCode
属性定义一个接口,并由拥有该接口的任何实体实现:
public interface ITableWithShortCode
{
public string ShortCode { get; set; }
}
public class Table1 : ITableWithShortCode
{
public long Id { get; set; }
public string ShortCode { get; set; }
}
public class Table2 : ITableWithShortCode
{
public long Id { get; set; }
public string ShortCode { get; set; }
}
现在,使用反射的功能
可以编写如下方法:
public bool IsExistShortCode(string shortCode)
{
using (var context = new AppDbContext())
{
/*
find all tables that are defined in your DbContext and are implemented ITableWithShortCode like:
public DbSet<Table1> Table1 { get; set; }
public DbSet<Table2> Table2 { get; set; }
...
*/
var properties = typeof(AppDbContext).GetProperties()
.Where(p => p.PropertyType.IsGenericType
&& typeof(ITableWithShortCode).IsAssignableFrom(p.PropertyType.GenericTypeArguments[0]));
foreach (var property in properties)
{
var contextProp = (IQueryable<ITableWithShortCode>)property.GetValue(context);
bool isExist = contextProp.Any(p => p.ShortCode == shortCode);
if (isExist)
return true;
}
return false;
}
}
public bool IsExistShortCode(字符串短码)
{
使用(var context=new AppDbContext())
{
/*
查找在DbContext中定义并使用短代码实现的所有表,如:
公共数据库集表1{get;set;}
公共数据库集表2{get;set;}
...
*/
var properties=typeof(AppDbContext).GetProperties()
.其中(p=>p.PropertyType.IsGenericType
&&typeof(ITableWithShortCode).IsAssignableFrom(p.PropertyType.GenericTypeArguments[0]);
foreach(属性中的var属性)
{
var contextProp=(IQueryable)property.GetValue(context);
bool isExist=contextProp.Any(p=>p.ShortCode==ShortCode);
如果(存在)
返回true;
}
返回false;
}
}
注意:您可以对这段代码进行一些优化,我更愿意将其保持在最简单的状态,以展示这一想法。但在生产环境中,例如,您可以在启动时轻松缓存DbContext属性,然后在启动后使用它,这很难,因为这是一件非常不寻常的事情。为什么在多个表中有一个唯一的列?我将创建一个包含单个列的新表,并使用所有其他表中的短代码填充它。使用该表检查唯一性。当然,在添加\删除\修改新记录时,您必须对其进行更新。话虽如此,我同意在不常见的情况下检查多个表中的唯一值。@Shahafo用一列创建一个新表,我也同意并检查它。@David Browne-Microsoft,该代码包含在某个地方工作的唯一权限,唯一代码将标记该权限