EF Core动态忽略列

问题描述 投票:2回答:2

下面,我试图根据在实体类中设置的属性来动态忽略数据库中的列。我想不出要做什么?????。我尝试过道具,但是不好。请帮助。

            System.Reflection.PropertyInfo[] props = typeof(MyTable).GetProperties();
            foreach (var prop in props)
            {
                object[] attrs = prop.GetCustomAttributes(true);
                foreach (object attr in attrs)
                {
                    DatabaseAttribute dbAttr = attr as DatabaseAttribute;
                    if (dbAttr != null)
                    {
                        string propName = prop.Name;
                        System.Version minVersion = new System.Version(dbAttr.MinVersion);
                        if (databaseVersion < minVersion)
                        {
                            // The database doesn't know about this property, ignore it
                            modelBuilder.Entity<MyTable>().Ignore(d => ?????);
                        }
                    }
                }
            }
c# ef-core-2.0
2个回答
0
投票

为什么不使用内置的NotMapped属性:https://entityframework.net/not-mapped

NotMapped属性用于指定不将实体或属性映射到数据库中的表或列

示例:

public class Author
{
    public int AuthorId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    [NotMapped]
    public string FullName 
    {
        get
        {
            return FirstName + " " + LastName;
        }
    }
}

0
投票
    modelBuilder.Entity<MyTable>().Ignore(prop.Name); 

或者您可以动态构建表达式

    modelBuilder.Entity<MyTable>().Ignore(Expression.Property(Expression.Parameter(typeof(MyTable)),prop));
© www.soinside.com 2019 - 2024. All rights reserved.