c# - 如何在不更改数据库模型的情况下在 Entity Framework 中添加新的实体属性

标签 c# asp.net-mvc entity-framework entity-framework-6

我是 Entity Framework 的新手。我从数据库优先方法开始,该方法创建了与我选择的表相对应的类。我正在使用 MVC。我的一个表中有一个 Date 列。我的要求是我想在我的 gridview(Grid MVC) 中显示日期,即如果获取的特定记录的日期是 2015 年 10 月 27 日,那么日期应该显示星期二。我想这样做而不在我的数据库中为当天添加额外的列。 有没有办法。任何帮助将不胜感激。

我生成的模型类如下:-

public partial class QnsNew1
    {
        public int Id { get; set; }
        public Nullable<System.DateTime> Date { get; set; }
        public Nullable<int> PersonelID { get; set; }
        public string CType { get; set; }
        public string Comments { get; set; }
        //public string Day { get; set; }//I want to avoid doing this
        public virtual Personnel Personnel { get; set; }
        public virtual Type Type { get; set; }
    }

最佳答案

更好的方法

虽然使用 Entity Framework 可以很容易地做到这一点,但正如其他答案所指出的那样,我 100% 承认,最好通过创建与常规实体分开的 ViewModel 来将表示/UI 模型与数据库模型分开,并且将计算出的属性放在那里。

如果您对 EF 感到困惑,请继续阅读

在 EntityFramework 数据库优先模式中,为数据库模型生成的类是分部类。您基本上可以在相同的程序集和命名空间中创建另一个具有相同名称的分部类,并在其中添加您的计算属性。

这是一个完整的示例(从此处的答案中借用了星期几的实现):

public partial class MyTable
{
    [NotMapped]
    public string DayOfWeek
    { 
        get 
        { 
            if (Date.HasValue)
                return DateTime.Now.DayOfWeek.ToString();
            else
                return null;
        } 
    }
}

It is important that you make sure the namespace is the same as the generated class. Also you will must annotate that property with NotMapped attribute so that EF does not attempt to map or save that property back to the database.

关于c# - 如何在不更改数据库模型的情况下在 Entity Framework 中添加新的实体属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33378720/

相关文章:

c# - Azure 媒体服务 Web 播放选项

asp.net-mvc - 如何从 .NET 应用程序创建全文搜索索引或目录?

javascript - 在 Javascript 中访问 Razor bool 变量时出错

c# - 删除 Entity Framework 中的所有实体

c# - 如何在一个 Controller 中使用 .net Core 创建几个 url

c# - 编写连接字符串以访问远程 SQL Server 数据库

c# - 每当将虚拟添加到属性时出现 SerializationException

asp.net-mvc - 跟踪 ASP.NET MVC 中的用户更改

c# - 如何在 C# 中同步值集合

javascript - 如何将简单的ID(jquery ajax)发布到asp.net mvc中的Action方法