获取父类中的Child Class属性

时间:2017-05-17 07:04:52

标签: c# asp.net-mvc entity-framework-6

我的应用程序中有两个控制器,数据库第一种方法

  

SampCutReqMaster.CS

launchWebAuthFlow

,接下来是

  

SamCutAssignmentMaster

public partial class SampCutReqMaster
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public SampCutReqMaster()
        {
            this.SamCutAssignmentMasters = new HashSet<SamCutAssignmentMaster>();
        }

        public decimal SampCutreqID { get; set; }
        public Nullable<decimal> BuyerID { get; set; }
        public Nullable<decimal> PatternRefID { get; set; }
        public Nullable<decimal> PatternStyleID { get; set; }
        public Nullable<decimal> SampleTypeID { get; set; }


        public virtual BuyerMaster BuyerMaster { get; set; }
        public virtual PatternStyle PatternStyle { get; set; }
        public virtual PatterRefMaster PatterRefMaster { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<SamCutAssignmentMaster> SamCutAssignmentMasters { get; set; }
        public virtual SampleType SampleType { get; set; }
    }

我创建了一个带有SampCutReqMaster

索引视图的控制器
 public partial class SamCutAssignmentMaster
    {
        public decimal CutAssignID { get; set; }
        public decimal SampCutreqID { get; set; }
        public System.DateTime ReceivedDate { get; set; }
        public string ReceivedBy { get; set; }
        public Nullable<decimal> PatternMasterID { get; set; }                 

        public virtual PatternMaster PatternMaster { get; set; }
        public virtual SampCutReqMaster SampCutReqMaster { get; set; }
    }

我想得到&#34;收到他们&#34; SamcutAssignmentMaster(子类)在SamCutReqMaster(Parent)的视图中。但SamcutAssignmentMaster中可能没有与SamCutReqMaster相关的数据(FK是SamCutReqID)

在索引视图下面我需要访问SamcutAssignmentMaster.receivedBy

public class SampCutReqMastersController : Controller
    {
        private ArtEntities db = new ArtEntities();
    // GET: SampCutReqMasters
    public ActionResult Index()
        {
            var sampCutReqMasters = db.SampCutReqMasters.Include(s => s.BuyerMaster).Include(s => s.PatternStyle).Include(s => s.PatterRefMaster).Include(s => s.SampleType).Include(s=>s.SamCutAssignmentMasters);

            var sampCutReqMasterssort = sampCutReqMasters.ToList().OrderByDescending(a => a.AddedDate);
            return View(sampCutReqMasterssort.ToList());
        }
}

1 个答案:

答案 0 :(得分:1)

确定。您的类型仍然是接口ICollection时,您无法访问属性。在通过索引访问集合的属性之前,需要将其强制转换为具体类型。

 @for (var adCounter = 0; adCounter <= (Model.SamCutAssignmentMasters.Count - 1); adCounter++)
 {
    @Html.DisplayFor(x => ((List<SamCutAssignmentMaster>)x.SamCutAssignmentMasters)[adCounter].ReceivedBy)
 }

按照上面的说法将类型转换为列表,您应该看到属性。

注意:您在视图中使用DisplayFor。如果您打算发布此视图的内容,除非您对每个项目都有隐藏控件或切换到TextBoxFor,否则模型将不会绑定。您还需要for(Counter)语法来绑定集合中的项目。

希望有所帮助。