避免将属性映射到表

时间:2012-09-09 08:01:17

标签: c# .net entity-framework ef-code-first

有人能告诉我如何使用代码优先方法避免将某些属性从我的模型映射到表吗?

示例:

public class Post
{
    [Key]
    public int Id { get; set; }

    [Display(Name = "Posted")]
    public DateTime Created { get; set; }

    [Display(Name = "Modified")]
    public DateTime? Modified { get; set; }

    [Required]
    [MaxLength(256)]
    public string Title { get; set; }

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

    public int? UserId { get; set; }

    public string UserName { get; set; }

    public virtual ICollection<Comment> Comments { get; set; }

    public virtual ICollection<Tag> Tags { get; set; } 
}

我希望UserName不映射到表中。 EF有可能与否?

2 个答案:

答案 0 :(得分:4)

添加

[NotMapped] 

属性为所需属性:

public class Post
{
    [Key]
    public int Id { get; set; }

    [Display(Name = "Posted")]
    public DateTime Created { get; set; }

    [Display(Name = "Modified")]
    public DateTime? Modified { get; set; }

    [Required]
    [MaxLength(256)]
    public string Title { get; set; }

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

    public int? UserId { get; set; }

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

    public virtual ICollection<Comment> Comments { get; set; }

    public virtual ICollection<Tag> Tags { get; set; } 
}

答案 1 :(得分:3)

首先在代码中,覆盖DbContext派生类中的OnModelCreating方法:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{   
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Post>().Ignore(p => p.UserName);
}