代码改变世界

Entity Framework 6 中如何获取 EntityTypeConfiguration 的 Edm 信息?(五)

  音乐让我说  阅读(266)  评论(0编辑  收藏  举报

直接贴代码了:

 NewsInfo 实体类:

复制代码
    public class NewsInfo
    {
        public int NewsInfoId { get; set; }
        public string NewsInfoTitle { get; set; }

        public int? NewsTypeId { get; set; }

        public virtual NewsType NewsTypeInfo { get; set; }
    }
复制代码

 

 NewsType 实体类:

 

复制代码
    public class NewsType
    {
        public int TypeId { get; set; }

        //[MaxLength(50)]
        public string TypeName { get; set; }

        /// <summary>
        /// 产品列表
        /// </summary>
        public virtual ICollection<NewsInfo> NewsInfoList { get; set; }
    }
复制代码

 

NewsInfoMap 实体映射类(利用 EF Fluent API 注册)

复制代码
    public class NewsInfoMap : EntityTypeConfiguration<NewsInfo>
    {
        public NewsInfoMap()
        {
            this.ToTable("NewsInfos");

            // Primary Key
            this.HasKey(t => t.NewsInfoId);

            // Properties
            this.Property(t => t.NewsInfoId)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            this.Property(t => t.NewsInfoTitle).HasColumnName("Title")
                .IsRequired()
                .HasMaxLength(255);

            // Relationships
            this.HasRequired(n => n.NewsTypeInfo)
                .WithMany(t => t.NewsInfoList)
                .HasForeignKey(t => t.NewsTypeId)
                .WillCascadeOnDelete(false);
        }
    }
复制代码

 

NewsTypeMap 实体映射类(利用 EF Fluent API 注册)

复制代码
    public class NewsTypeMap : EntityTypeConfiguration<NewsType>
    {
        public NewsTypeMap()
        {
            this.ToTable("NewsTypes");

            // Primary Key
            this.HasKey(t => t.TypeId);

            // Properties
            this.Property(t => t.TypeId).HasColumnName("NewsTypeId")
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            this.Property(t => t.TypeName).HasColumnName("NewsTypeName")
                .HasMaxLength(255);
        }
    }
复制代码

 

NewContext

复制代码
    public class NewContext : DbContext
    {
        static NewContext()
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<NewContext>()); // 架构改变,自动删除,并新建数据库
        }

        public DbSet<NewsInfo> NewsInfos { get; set; }
        public DbSet<NewsType> NewsTypes { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Configurations.Add(new NewsInfoMap());
            modelBuilder.Configurations.Add(new NewsTypeMap());
        }
    }
复制代码

 

实际测试:

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
using CodeFirstDemo.Extensions;
using System.Data.Entity.ModelConfiguration;
using System.ComponentModel.DataAnnotations.Schema;
using System.Reflection;
using static CodeFirstDemo.Extensions.MetaHelper;

namespace CodeFirstDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var db = new NewContext())
            {
                //TestInsertAndQuery(db);
                TestGetDbContextMetaInfo(db);

                Console.ReadKey();
            } 
        }

        static void TestInsertAndQuery(NewContext db)
        {
            Console.Write("Please Input News Type Title: ");
            var name = Console.ReadLine();

            var type_Model = new NewsType { TypeName = name };
            db.NewsTypes.Add(type_Model);
            db.SaveChanges();

            Console.Write("Please Input Search Type Name : ");
            var search_type = Console.ReadLine();
            var query = from b in db.NewsTypes
                        where b.TypeName == search_type
                        select b;

            Console.WriteLine("Query Result:");
            foreach (var item in query)
            {
                Console.WriteLine(item.TypeName);
            }
            Console.WriteLine("\n\n\n");
        }

        static void TestGetDbContextMetaInfo(NewContext db)
        {
            Console.WriteLine("DbContext Meta: \n");

            // 测试环境:Win10、SQL Server Express 2008、EntityFramework.6.1.0
            // 经过实际测试,下面的所有代码,只有在第一个调用 db.GetTableName<NewsInfo>(); 才会比较慢,因为这
            // 时候 EF 会从数据库中拿数据,后面的第二个(db.GetTableName<NewsType>()) 一直到结束都比较快了。可
            // 能是 EF 已经缓存了 EDM 信息,所以就比较快了。

            // Table Name
            string newsTableName = db.GetTableName<NewsInfo>();
            Console.WriteLine("NewsInfo TableName: " + newsTableName); // dbo.NewsInfos

            string NewTypeTableName = db.GetTableName<NewsType>();
            Console.WriteLine("NewsType TableName: " + NewTypeTableName); //dbo.NewsTypes

            Console.WriteLine("\n");

            // PK Name
            var newsPKNameDic = db.GetTableKeyColumns<NewsInfo>(); // key=DbColumnName, Value= C# Property Info
            Console.Write("newsPKName: ");
            PrintStringPropertyInfoDic(newsPKNameDic); // ( NewsInfoId: NewsInfoId )

            var newsTypePKNameDic = db.GetTableKeyColumns<NewsType>(); // key=DbColumnName, Value= C# Property Info
            Console.Write("newsTypePKName: ");
            PrintStringPropertyInfoDic(newsTypePKNameDic); // (NewsTypeId: TypeId )

            Console.WriteLine("\n");

            // all column name - property info
            var newsAllColumnNamePropInfoDic = db.GetTableColumns<NewsInfo>(); // key=DbColumnName, Value = C# Property Info
            Console.Write("news all column name - property info dictionary: ");
            PrintStringPropertyInfoDic(newsAllColumnNamePropInfoDic); //( NewsInfoId: NewsInfoId ),( Title: NewsInfoTitle ),( NewsTypeId: NewsTypeId )

            var newsTypeAllColumnNamePropInfoDic = db.GetTableColumns<NewsType>(); // key=DbColumnName, Value = C# Property Info
            Console.Write("news type all column name - property info dictionary: ");
            PrintStringPropertyInfoDic(newsTypeAllColumnNamePropInfoDic); //( NewsTypeId: TypeId ),( NewsTypeName: TypeName )

            Console.WriteLine("\n");

            // all column name - property name
            var newsAllColumnNamePropNameDic = db.GetPropertyColumnNames<NewsInfo>(); // key= C# Property Name, Value= DbColumnName
            Console.Write("news all column name - property name dictionary: ");
            PrintPkNameDicCore(newsAllColumnNamePropNameDic, null); //  ( NewsInfoId: NewsInfoId ),( NewsInfoTitle: Title ),( NewsTypeId: NewsTypeId )

            var newsTypeAllColumnNamePropNameDic = db.GetPropertyColumnNames<NewsType>(); // key= C# Property Name, Value= DbColumnName
            Console.Write("news type all column name - property name dictionary: ");
            PrintPkNameDicCore(newsTypeAllColumnNamePropNameDic, null); //  ( TypeId: NewsTypeId ),( TypeName: NewsTypeName )

            Console.WriteLine("\n");

            //经过测试,下面这 3 行代码发生了异常!
            //List<EntityKey> newDependentList = db.GetDependentTypes(typeof(NewsInfo));
            //Console.WriteLine("news dependent types: ");
            //PrintEntityKeyList(newDependentList);
            //Console.WriteLine("");

            List<EntityKey> newsTypeDependentList = db.GetDependentTypes(typeof(NewsType));
            // newsTypeDependentList 里面的信息如下:
            // type= C#实体类的名称,比如:NewsInfo。
            // Keys = 一个或外键字段对应的 C# Property 信息。比如:Nullable<int> NewsTypeId
            Console.WriteLine("news type dependent types: ");
            PrintEntityKeyList(newsTypeDependentList); // ( NewsInfo: { type=Nullable`1, name=NewsTypeId  } )

            Console.WriteLine("\n");

            //
            var newsPKColumnIdentityDic = db.GetComputedColumnNames<NewsInfo>();
            Console.Write("news primaryKey column name - identity dictionary: ");
            PrintPkNameDicCore(newsPKColumnIdentityDic, null); //  ( NewsInfoId: True )

            var newsTypePKColumnIdentityDic = db.GetComputedColumnNames<NewsType>();
            Console.Write("news type primaryKey column name - identity dictionary: ");
            PrintPkNameDicCore(newsTypePKColumnIdentityDic, null); //  ( NewsTypeId: True )

            Console.WriteLine("\n");

            //
            string newsInfoTitleColumnName = db.GetColumnName<NewsInfo>("NewsInfoTitle");
            Console.Write("newsInfo title column name: " + newsInfoTitleColumnName); // Title
            Console.WriteLine("");

            string typeNameColumnName = db.GetColumnName<NewsType>("TypeName");
            Console.Write("NewsType typeName column name: " + typeNameColumnName); // NewsTypeName
            Console.WriteLine("");

            Console.WriteLine("\n");

            
        }

        static void PrintStringPropertyInfoDic(Dictionary<string, PropertyInfo> infoDic)
        {
            PrintPkNameDicCore<PropertyInfo>(infoDic, t => t.Name);
        }

        static void PrintPkNameDicCore<T>(Dictionary<string, T> infoDic, Func<T, object> printCoreFunc)
        {
            int i = 0;
            foreach (var item in infoDic)
            {
                if (i > 0)
                {
                    Console.Write(",");
                }
                Console.Write("( {0}: {1} )", item.Key, printCoreFunc == null ? item.Value : printCoreFunc(item.Value));
                i++;
            }
            Console.WriteLine("");
        }

        static void PrintEntityKeyList(IEnumerable<EntityKey> entityKeyList)
        {
            int i = 0;
            foreach (var item in entityKeyList)
            {
                if (i > 0)
                {
                    Console.Write(",");
                }
                string keyTextInfo = string.Join(",", item.Keys.Select(c => string.Format("type={0}, name={1} ", c.PropertyType.Name, c.Name)));
                Console.Write("( {0}: {{ {1} }} )", item.Type.Name, keyTextInfo);
                i++;
            }
            Console.WriteLine("");
        }
    }

    
}
复制代码

 

运行效果图

 

谢谢浏览!

点击右上角即可分享
微信分享提示