当前位置:Gxlcms >
数据库问题 >
EF 中获取 TableAttribute的值,即数据库中真实的表名
EF 中获取 TableAttribute的值,即数据库中真实的表名
时间:2021-07-01 10:21:17
帮助过:3人阅读
print?
- [Table(Name = "MyTableName")]
- public class MyClass
- {
- }
[Table(Name = "MyTableName")]
public class MyClass
{
}
现我想获取 MyTableName,可以这样来办:
[csharp] view plain
copy
print?
- using System.Data.Linq.Mapping;
-
- namespace MyEF
- {
- class Program
- {
- static void Main(string[] args)
- {
- string name = typeof(MyClass).GetAttributeValue((TableAttribute ta) => ta.Name);
- Console.WriteLine(name);
-
- Console.Read();
- }
- }
-
- public static class AttributeExtensions
- {
- public static TValue GetAttributeValue<TAttribute, TValue>(
- this Type type,
- Func<TAttribute, TValue> valueSelector)
- where TAttribute : Attribute
- {
- var att = type.GetCustomAttributes(
- typeof(TAttribute), true
- ).FirstOrDefault() as TAttribute;
- if (att != null)
- {
- return valueSelector(att);
- }
- return default(TValue);
- }
- }
-
- [Table(Name = "MyTableName")]
- public class MyClass
- {
- }
- }
EF 中获取 TableAttribute的值,即数据库中真实的表名
标签: