繁体   English   中英

使用Entity Framework CodeFirst映射表和视图

[英]Map table and views with Entity Framework CodeFirst

我的数据库中有1个表和2个视图(PeopleView和ProjectView)。

名为Hours的表具有作为对视图的“引用”的列。

[Id] [int] IDENTITY(1,1) NOT NULL,
[Date] [date] NOT NULL,
[PeopleId] [int] NOT NULL, // Reference to PeopleView
[ProjectId] [nvarchar](max) NOT NULL, // Reference to PrijectView
[Hour] [int] NOT NULL,

我用视图创建外键是不可能的。 所以我的问题是如何在EntityFramework中为这种情况创建映射。

当我从数据库获得一些Hours实体时,我想像这样访问Project实体:

hour.project.name
hour.project.id

有可能的 ?

小时实体:

   public class Hour : Entity<int>
{
    [Column(TypeName = "date")]
    [Required]
    public virtual DateTime Date { get; set; }


    public virtual PeopleView People { get; set; }
    [Required]
    public virtual int? PeopleId { get; set; }


    public virtual ProjectView Project { get; set; } // How to access project object from hour object when Project is a View in DB ?
    [Required]
    public virtual string ProjectId { get; set; }


    [Required]
    [Column("Hour")]
    public virtual int Hours { get; set; }


}

ProjectView实体:

[Table("ProjectView")]
public partial class ProjectView : Entity<string>
{
    [Key]
    [Column(Order = 0)]
    [StringLength(50)]
    public override string Id { get; set; }

    [StringLength(255)]
    public string Name { get; set; }

    [Column(Order = 1)]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Offer { get; set; }
}

是的,您绝对可以做到这一点。 您可以使用ForeignKey属性/注释来告诉框架如何建立类之间的关系(即使数据库中没有实际的外键)。

像这样:

[ForeignKey("PeopleId")]
public virtual PeopleView People { get; set; }
[Required]
public virtual int? PeopleId { get; set; }


[ForeignKey("ProjectId")]
public virtual ProjectView Project { get; set; } 
[Required]
public virtual string ProjectId { get; set; }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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