首页 > 学院 > 开发设计 > 正文

EntityFramework6.0对枚举的支持/实体添加后会有主键反回

2019-11-14 16:28:50
字体:
来源:转载
供稿:网友

实验

直接上代码,看结果

实体类

[Flags]    public enum FlagsEnum    {        Day = 1,        Night = 2    }    public class EntityWithEnum    {        public int ID { get; set; }        public FlagsEnum ValidTime { get; set; }    }

 

数据库上下文

public partial class CodeFirstModel : DbContext   {        public CodeFirstModel()            : base("name=CodeFirstModel")        {        }        public virtual DbSet<EntityWithEnum> EntityWithEnum { get; set; }}

Sql server LocalDb的连接字符串

<connectionStrings>    <add name="CodeFirstModel" connectionString="data source=(LocalDb)/MSSQLLocalDb;initial catalog=TestDb;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework" PRoviderName="System.Data.SqlClient" />  </connectionStrings>

 

主函数

 

static void Main(string[] args)        {            //CreateDatabaseIfNotExists            //DropCreateDatabaseIfModelChanges            //DropCreateDatabaseAlways            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<CodeFirstModel>());            using (var context = new CodeFirstModel())            {                context.Database.Initialize(true);            }            using(CodeFirstModel db = new CodeFirstModel())            {        EntityWithEnum entity = new EntityWithEnum() { ValidTime = FlagsEnum.Day };                db.EntityWithEnum.Add(entity);                entity = new EntityWithEnum() { ValidTime = FlagsEnum.Night };                db.EntityWithEnum.Add(entity);                entity = new EntityWithEnum() { ValidTime = FlagsEnum.Night| FlagsEnum.Day };                db.EntityWithEnum.Add(entity);                db.SaveChanges();                Console.WriteLine("{0}:/t{1}", entity.ID, entity.ValidTime);                Console.WriteLine("-------------------");                var entitys = from e in db.EntityWithEnum                              where e.ValidTime.HasFlag(FlagsEnum.Day)                              select e;                foreach (var item in entitys)                {                    Console.WriteLine("{0}:/t{1}", item.ID, item.ValidTime);                }                            }            Console.ReadKey(true);}

运行结果

捕获

 

结论

Entity Framework 6.0 的 LINQ 是可以直接写 枚举的 HasFlags 方法的.

Add 的实体在 数据库保存后,会将数据库生成好的主键读出来.不用再写LINQ 再查一遍了.


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表