简体   繁体   中英

Exclude a column from DbContext using ASP.NET MVC and EntityFramework

I have the following model:

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;
    }
}

and Db context:

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

and my table looks like:

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)
);

As you see, I added a new property called ConfirmEmail attached to Movie model. But I didn't add to table and I don't want to.

When run application, an error is occured:

Unknown column name ConfirmEmail .

Does it is possible to exclude that ConfirmEmail from context ?

It is just used as parameter to be compared to Email property.

Thanks

Use the NotMappedAttribute

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM