【问题标题】:Adding a virtual column to Table in Entity Framework? [duplicate]在实体框架中向表中添加虚拟列? [复制]
【发布时间】:2015-08-31 11:07:01
【问题描述】:

我有以下 dbcontext.cs 和相应的 table.cs,它们使用实体框架在我的 MVC 中定义 DAL。

我的数据库中的 List 表没有 C 列,但我希望实体从 DB 中获取 ID、A、B 值并从代码中获取 C。如果可以的话,这可能吗?最好的方法是什么。

以下代码未能给出异常“Invalid Coloumn C”。

我可以考虑的另一种方法是声明另一个实体 ex:ListEntity2 并在从 ListEnity 查询后添加值,我认为这是一个好方法,但只是想要了解任何其他可能性。

table.cs:

 [Table("List")]
    public class ListEntity
    {
        [Key]
        public int ID { get; set; }
        public string A { get; set; }
        public int B { get; set; }
        private string name;
        public virtual string C
        {
            get 
            {
                return name;
            }
            set
            {
               name=value ;
            }
        }
    }

dbcontext.cs:

public DbSet<ListEntity> List { get; set; }

【问题讨论】:

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


【解决方案1】:

您可以尝试使用NotMapped 属性(Documentation

[...] 表示应从数据库映射中排除属性或类。

例如:

using System.ComponentModel.DataAnnotations.Schema;

[Table("List")]
public class ListEntity
{
    [Key]
    public int ID { get; set; }
    public string A { get; set; }
    public int B { get; set; }

    private string name;

    [NotMapped]
    public string C
    {
        get { return name; }
        set { name = value; }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-24
    • 2015-02-11
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 2011-09-21
    相关资源
    最近更新 更多