Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过fluentapi公开外键_C#_Linq_Entity Framework_Foreign Keys_Ef Fluent Api - Fatal编程技术网

C# 通过fluentapi公开外键

C# 通过fluentapi公开外键,c#,linq,entity-framework,foreign-keys,ef-fluent-api,C#,Linq,Entity Framework,Foreign Keys,Ef Fluent Api,好的,我有很多对象,但是举个例子来说,它只有两个对象,公司和人,为了简单的例子,我删掉了大部分的道具: public class Company { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } public List<People> Peoples { get; set; } [StringLength(100

好的,我有很多对象,但是举个例子来说,它只有两个对象,公司和人,为了简单的例子,我删掉了大部分的道具:

public class Company {
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public List<People> Peoples { get; set; }

    [StringLength(100)]
    [Required]
    public string Bname { get; set; }
}
我不喜欢使用数据注释,所以我可以将地图分开放置。 我的简化映射是:

class CompanyMap : EntityTypeConfiguration<Company> {
        public CompanyMap() {

            HasMany(p => p.Peoples)
           .WithRequired();
}}
但如果我尝试用linq查询它,并将它们连接起来:

var tmp2 = from c in db.Companies
           join p in db.Person
             on c.Id equals p.
这就是我的问题,People对象并没有从db中暴露它的外键,所以我不能像这样连接它们

所以我的问题是,我可以将fluentapi创建的fk公开给我的对象模型,这样我就可以linq它了吗

或者我应该使用lambda one,并以某种方式将其映射到我的viewmodel,这样它就不会为此视图生成不需要的列了吗?

首先,将FK属性(
CompanyId
)和导航属性(
Company
)添加到您的
人员
实体:

 public class People {

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    //...
    public int CompanyId {get;set}
    public virtual Company Company{get;set;}
}
然后,将Fluent Api关系配置移动到
PeopleMap
类中,并以这种方式修改该配置(同时映射与
People
表中的FK列同名的FK属性):


我想强调的是,当这些导航就绪时,不需要连接。这是真的,OP可能还不知道如何使用它们,因此它正在尝试将sql查询转换为linq查询。这有助于OP更好地理解如何使用导航属性。谢谢你们的博尼斯输入!
var tmp2 = from c in db.Companies
           join p in db.Person
             on c.Id equals p.
 public class People {

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    //...
    public int CompanyId {get;set}
    public virtual Company Company{get;set;}
}
public class PeopleMap : EntityTypeConfiguration<People> {
        public CompanyMap() {

            Property(p => p.CompanyId)
                    .HasColumnName("CompanyId");//remember change the name for the real FK column 

            HasRequired(p=>p.Company)
           .WithMany(c=>c.Peoples)
           .HasForeignKey(p=>p.CompanyId);
         }
}
var tmp2 = from c in db.Companies
           join p in db.Person on c.Id equals p.CompanyId
           //...