我有一个班级,Rate
可以有两个位置; LocationTo
和LocationFrom
。位置应该是页面上的下拉列表。
我的模特看起来像这样:
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; }
}
我在这里想的是正确的吗?
这是对的哦?什么是公共虚拟位置LocationTo {get;组;做什么?
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; }
}
答案 0 :(得分: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可以找到从位置到费率的方式
编辑:下拉列表示例
好的,问题稍有改动:-)要添加下拉列表,您可以这样写。
@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的变量。