使用ASP.NET MVC和EntityFramework从DbContext中排除列

时间:2013-12-04 13:17:47

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

我有以下型号:

public class Movie
{
    public int Id { get; set; }

    [Required]
    public string Title { get; set; }

    [DataType(DataType.DateTime)]
    [Display(Name = "Release date")]
    [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}")]
    public DateTime ReleaseDate { get; set; }

    [Required]
    public string Genre { get; set; }

    [Required]
    [Range(1, 20)]
    public decimal Price { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    public string Email
    {
        get;
        set;
    }

    [Compare("Email")]
    public string ConfirmEmail
    {
        get;
        set;
    }
}

和Db上下文:

public class MovieDbContext : DbContext
{
    public DbSet<Movie> Movies { get; set; }
}

我的表格如下:

CREATE TABLE [dbo].[Movies] (
    [Id]          INT            IDENTITY (1, 1) NOT NULL,
    [Title]       NVARCHAR (50)  NOT NULL,
    [ReleaseDate] DATETIME       NOT NULL,
    [Genre]       NVARCHAR (50)  NOT NULL,
    [Price]       DECIMAL (6, 2) NOT NULL,
    [Email]       NVARCHAR (100) DEFAULT ('') NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

如您所见,我添加了一个名为ConfirmEmail的新属性,附加到Movie模型。但我没有添加到桌面,我不想。

运行应用程序时,会发生错误:

未知列名ConfirmEmail

是否可以从上下文中排除ConfirmEmail

它仅用作与Email属性进行比较的参数。

由于

1 个答案:

答案 0 :(得分:3)

使用NotMappedAttribute

[NotMapped]
public string ConfirmEmail {get;set;}