实验
直接上代码,看结果
实体类
[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 再查一遍了.
时间: 2024-10-10 11:31:53