实体框架代码首先一对多可选,具有流畅的映射

时间:2014-06-29 04:50:34

标签: c# entity-framework

我有以下C#模型,其中公司存在于给定的TimeZone中。

[Table("Company")]
public class Company
{
    [Key]
    public int Id { get; set; }

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

    [Required]
    public TimeZone TimeZone { get; set; }

}

[Table("TimeZone")]
public class TimeZone
{
    [Key]
    public int Id { get; set; }

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

}

在我预先存在的SQL数据库中,TimeZone表是一个查找表,旨在由公司表和任何需要TimeZone的东西引用。因此,一对多关系中的外键在公司中。

CREATE TABLE [dbo].[Company](
[Id]            [int] IDENTITY(1,1)     NOT NULL,
[Name]          [nvarchar](500)         NOT NULL,
[TimeZoneId]    [int]                   NOT NULL REFERENCES dbo.TimeZone(Id)) 

CREATE TABLE [dbo].TimeZone(
[Id]            [int] IDENTITY(1,1)     NOT NULL,
[Name]          [nvarchar](500)         NOT NULL)

如何使用EF Fluent API(我使用EF 6)映射他,以便我可以使用Company.TimeZone.Name?

2 个答案:

答案 0 :(得分:2)

尝试这样的事情:

public class CompanyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder builder)
    {
        builder.Entity<Company>()
            .HasRequired(c => c.TimeZone)
            .WithMany()
            .HasForeignKey(c => c.TimeZoneId);

        base.OnModelCreating(builder);
    }

}

[Table("Company")]
public class Company
{
    [Key]
    public int Id { get; set; }

    public int TimeZoneId { get; set; }

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

    // this will be navigation property
    public TimeZone TimeZone { get; set; }

}

[Table("TimeZone")]
public class TimeZone
{
    [Key]
    public int Id { get; set; }

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

}

答案 1 :(得分:0)

您需要将延迟加载的TimeZone属性声明为虚拟,如下所示:

[Table("Company")]
public class Company
{
    [Key]
    public int Id { get; set; }

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

    [Required]
    public virtual TimeZone TimeZone { get; set; }

}

[Table("TimeZone")]
public class TimeZone
{
    [Key]
    public int Id { get; set; }

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

}