C# 在ASP.NET MVC中如何使用另一个模型作为属性

C# 在ASP.NET MVC中如何使用另一个模型作为属性,c#,asp.net-mvc,entity-framework,C#,Asp.net Mvc,Entity Framework,所以我有两个模型,一个是公司,一个是省 [Table("Company")] public class Company { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int ID { get; set; } public string Name { get; set; } public int ProvinceID { get; set; }

所以我有两个模型,一个是公司,一个是省

[Table("Company")]
public class Company {
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    public string Name { get; set; }
    public int ProvinceID { get; set; }
    public ProvinceModel Province{
        get {
            // ????
        }
    }
}
public class CompanyContext : MyXsiteContext {
    public DbSet<Company> Companies { get; set; }
}
[表格(“公司”)]
公营公司{
[关键]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
公共int ID{get;set;}
公共字符串名称{get;set;}
public int ProvinceID{get;set;}
公共省示范省{
得到{
// ????
}
}
}
公共类CompanyContext:MyXsiteContext{
公共数据库集公司{get;set;}
}
这是我的省:

[Table("Province")]
public class ProvinceModel {
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    public string Name { get; set; }
}
public class ProvinceContext : MyXsiteContext {
    public DbSet<ProvinceModel> Provinces { get; set; }
}
[表(“省”)]
公共类ProvinceModel{
[关键]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
公共int ID{get;set;}
公共字符串名称{get;set;}
}
公共类ProvinceContext:MyXsiteContext{
公共数据库集{get;set;}
}

如何让只保存ProvinceID的公司引用省对象,以便我可以在视图中引用Province.name?

您似乎希望这样做与导航属性的描述类似

所以在链接中,他们描述了课程->部门,但对你来说,是公司->省

[Table("Company")]
public class Company {
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    public string Name { get; set; }
    public int ProvinceID { get; set; }
    public ProvinceModel Province{
        get {
            // ????
        }
    }
}
public class CompanyContext : MyXsiteContext {
    public DbSet<Company> Companies { get; set; }
}

另一方面,如果您要引用Province.Name,在您的视图中,您可能会遇到一个问题,因此这可能是需要解释的(取决于您的特定用例,我不是100%了解,只是强调它是一个潜在的“东西”)

请注意,这可能是关于实体框架,而不是MVC,因为您的“模型”是数据库感知实体。好的,我将向标记中添加实体框架。请停止将“ASP.NET MVC”简单地称为“MVC”。一个是框架,另一个是独立于语言的设计模式。这就像把IE称为“互联网”是的,你给我指明了正确的方向,我可以在我的公司视图中加载省的下拉列表。