【问题标题】:Avoiding mapping property to table避免将属性映射到表
【发布时间】:2012-09-09 08:01:16
【问题描述】:

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

例子:

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里有没有可能?

【问题讨论】:

  • 对不起!我忘了这个:(((。我会在未来改进它。

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


【解决方案1】:

添加一个

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

【讨论】:

    【解决方案2】:

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {   
        base.OnModelCreating(modelBuilder);
    
        modelBuilder.Entity<Post>().Ignore(p => p.UserName);
    }
    

    【讨论】:

    • 好的!我们可以讨论 [NotMapped] attr 之间的区别吗?和 modelBuilder.Entity().Ignore(p => p.UserName);还是一样的东西?
    • 是一样的,但是这样你就不需要在定义实体的程序集中依赖 EntityFramework.dll。我经常喜欢在自己的程序集中定义我的实体类,以便可以单独测试它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 2012-10-13
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多