首先在EF 7代码中创建POCO类

时间:2016-05-23 19:01:40

标签: entity-framework entity-framework-core

说我有三张桌子。现有数据库中的设置,设施和FacilitySettingOverride。样本数据:

Settings table

ID   Name     Value
1    test1    true
2    test2    true

Facilities table

ID    Name
163   Demo1
164   Demo2

FacilitySettingOverride
FacilityId      SettingId   Value
163               2         False
164               1         False
164               2         False

FacilitySettingOverride有两个外键--- FacilityId和SettingId。另外,我想为FacilitySettingOverride创建一个复合键。

我只是不知道如何制作它。我的主要代码。

[Table("Settings")]
public class Setting
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }

    public FacilitySettingOverride FacilitySettingOverride { get; set; }
}

[Table("Facilities")]
public class Facility
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public  virtual ICollection<FacilitySettingOverride> FacilitySettingOverrides { get; set; }
}

[Table("FacilitySettingOverride")]
public class FacilitySettingOverride
{
    [Key]
    [ForeignKey("FacilityId")]
    public int FacilityId { get; set; }

    public string Value { get; set; }
    [ForeignKey("SettingId")]
    public int SettingId { get; set; }

    public virtual Facility Facility { get; set; }
    public virtual Setting Setting { get; set; }

我猜这是错的。谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

查看您的数据和说明,SettingsFacility都与FacilitySettingOverride具有一对多的关联。所以Setting不应该有财产......

public FacilitySettingOverride FacilitySettingOverride { get; set; }

...但是FacilitySettingOverride的集合,就像Facility一样。

这应该是正确的班级模型:

[Table("Settings")]
public class Setting
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }    
    public virtual ICollection<FacilitySettingOverride> FacilitySettingOverrides { get; set; }
}

[Table("Facilities")]
public class Facility
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<FacilitySettingOverride> FacilitySettingOverrides { get; set; }
}

[Table("FacilitySettingOverride")]
public class FacilitySettingOverride
{
    [Key, Column(Order = 1)]
    [ForeignKey("Facility")]
    public int FacilityId { get; set; }

    [Key, Column(Order = 2)]
    [ForeignKey("Setting")]
    public int SettingId { get; set; }

    public virtual Facility Facility { get; set; }
    public virtual Setting Setting { get; set; }
    public string Value { get; set; }
}

KeyAttributeColumnAttribute[Key, Column(Order = 1)])的组合用于复合主键。

这是EF从中创建的数据库模式:

enter image description here