0

我有一个班级,Rate可以有两个地点;LocationToLocationFrom。位置应该是页面上的下拉列表。

我的模型如下所示:

public class Rate
{
    [Key]
    public int Id { get; set; }
    public string RateName { get; set; }
    public int LocationToId { get; set; }
    public int LocationFromId { get; set; }
    public virtual Location LocationTo { get; set; }
    public virtual Location LocationFrom { get; set; }
}

public class Location
{
    [Key]
    public int Id { get; set; }
    public string LocationName { get; set; }
    public virtual ICollection<Rate> Rates { get; set; }
}

我在这里想对了吗?


这是正确的ohlin吗?public virtual Location LocationTo { 得到什么?放; } 做?

   public class Location
{
    [Key]
    public int Id { get; set; }
    public string LocationName { get; set; }
    [InverseProperty("LocationToId")]
    public virtual ICollection<Rate> ToRates { get; set; }
    [InverseProperty("LocationFromId")]
    public virtual ICollection<Rate> FromRates { get; set; }
}
public class Rate
{
    [Key]
    public int Id { get; set; }
    public string RateName { get; set; }
    public int LocationToId { get; set; }
    public int? LocationFromId { get; set; }
    public virtual Location LocationTo { get; set; }
    public virtual Location LocationFrom { get; set; }
}
public class dc : DbContext
{
    public DbSet<Location> Locations { get; set; }
    public DbSet<Rate> Rates { get; set; }

}
4

1 回答 1

1

您的模型的一个问题是每个 Rate 都有两个 Location 引用,您需要通过添加一些属性来帮助 EF。Rate 类中外部 id 的默认名称应该是 LocationId,但是您有两个引用,因此需要给它们单独的名称。没有错...

但是您需要在 Location 模型中进行一些更改:

public class Location
{
    [Key]
    public int Id { get; set; }
    public string LocationName { get; set; }
    [InverseProperty("LocationToId")]
    public virtual ICollection<Rate> ToRates { get; set; }
    [InverseProperty("LocationFromId")]
    public virtual ICollection<Rate> FromRates { get; set; }
}

通过添加InverseProperty属性,EF 可以找到从 Location 到 Rate 的方式

编辑:下拉列表示例

好的,问题发生了一点变化 :-) 要添加下拉列表,您可以用这种方式编写。

@model Rate
@Html.DropDownListFor(model => model.LocationFromId, ((IEnumerable<Location>)ViewBag.PossibleLocations).Select(option => new SelectListItem {
    Text = Html.DisplayTextFor(_ => option).ToString(), 
    Value = option.Id.ToString(),
    Selected = (Model != null) && (option.Id == Model.LocationFromId)
}), "Choose...")

要完成这项工作,您需要做的是在传递给 View 之前,在 Controller 的 ViewBag 中创建一个名为 PossibleLocations 的变量。

于 2013-06-18T15:22:28.873 回答