2

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

例子:

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 中是否可能?

4

2 回答 2

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; } 
}
于 2012-09-09T08:03:32.140 回答
3

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

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

    modelBuilder.Entity<Post>().Ignore(p => p.UserName);
}
于 2012-09-09T08:05:12.217 回答