【问题标题】:check if a property is ignored by EntityFramework检查 EntityFramework 是否忽略属性
【发布时间】:2013-02-08 13:16:58
【问题描述】:

使用带有 POCO 的 EntityFramework 4.3。 如何检查模型上的属性是否被忽略。

在我的 DBContext 类层次结构中,我忽略了一个属性

modelBuilder.Entity<EClass>().Ignore (f => f.IgnoredProperty());

在我的 BaseContext 类中,我需要检查该属性是否被忽略。

private void ProcessGlobalConvention(DbModelBuilder modelBuilder, IGlobalConvention convention)
{
    modelBuilder.Entity<typeof(this.GetType())>("Ignored Property");
}

我该怎么做?

谢谢

【问题讨论】:

    标签: entity-framework entity-framework-4 entity-framework-4.3


    【解决方案1】:

    使用 EF 电动工具http://www.infoq.com/news/2013/10/ef-power-tools-beta4 查看您的模型。房产在吗?

    创建一个数据库。有柱子吗?

    查看Database.LogSqlEventshttp://blog.oneunicorn.com/2013/05/08/ef6-sql-logging-part-1-simple-logging/并解析sql看是否出现字段名...

    ....除非您真的想要代码解决方案...?

    在什么情况下

    新建你的 DbContext 创建一条记录并将其添加到相关的 DbSet 获取 DbEntityEntry 查看 CurrentValues.PropertyNames。你的房产在吗?

        [TestMethod]
        public void CreateDatabase()
        {
            Database.SetInitializer(new DropCreateDatabaseAlways<HomesContext>());
    
            var db = new HomesContext();
    
            Assert.IsFalse(db.Homes.Any());
    
            var home = db.Homes.Create();
    
            db.Homes.Add(home);
    
            var entry = db.Entry(home);
    
            Assert.IsTrue(entry.CurrentValues.PropertyNames.Contains("MaxResidents"));
            Assert.IsTrue(entry.CurrentValues.PropertyNames.Contains("MaxStaff"));
            Assert.IsFalse(entry.CurrentValues.PropertyNames.Contains("CurrentResidents"));
            Assert.IsFalse(entry.CurrentValues.PropertyNames.Contains("CurrentStaff"));
    
        }
    public class HomesContext:DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Home>().Ignore(x => x.CurrentResidents);
    
            base.OnModelCreating(modelBuilder);
        }
        public DbSet<Home> Homes { get; set; }
    }
    
    public class Home
    {
        public int HomeId { get; set; }
        public string HomeName { get; set; }
    
        public int MaxResidents { get; set; }
        public int MaxStaff { get; set; }
    
        public int CurrentResidents { get; set; }
    
        [NotMapped]
        public int CurrentStaff { get; set; }
    }
    

    【讨论】:

    • 是的,我需要一个代码解决方案。我可以找到 [NotMapped] 属性,但是当您使用模型构建器忽略列时,我无法检测到。
    猜你喜欢
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-02
    相关资源
    最近更新 更多