-->

Can't retrieve ManyToMany field value in ASP.N

2019-09-18 02:42发布

问题:

I have 2 models PosTransactionModel and PosItemModel which build on Postgresql via EntityFramework6, they reference each as a ManyToMany relationship.

public class PosTransactionModel
{
    public int Id { get; set; }
    public ICollection<PosItemModel> SaleItems { get; set; }
    ...
    ...
}

public class PosItemModel
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]       
    public int ItemId { get; set; }
    public ICollection<PosTransactionModel> SoldInPosTransactions { get; set; }
}

I can see 3 tables has been successfully created for maintain the data and relationship:

with some testing data filled in database table, I can see the PosTransactionModel and its SaleItems data can be correctly published via a WebAPI interface, and client side testing http client can get the correct JSON data:

Now, I'm trying to build an admin site for manage these data by ASP.NET Dynamic Data template, the problem is that ManyToMany SaleItems field always empty against the testing data:

This is the default template code for ManyToManyField:

public partial class ManyToManyField : System.Web.DynamicData.FieldTemplateUserControl
{
    protected override void OnDataBinding(EventArgs e)
    {
        base.OnDataBinding(e);

        object entity;
        ICustomTypeDescriptor rowDescriptor = Row as ICustomTypeDescriptor;
        if (rowDescriptor != null)
        {
            entity = rowDescriptor.GetPropertyOwner(null);
        }
        else
        {
            entity = Row;
        }

        var entityCollection = Column.EntityTypeProperty.GetValue(entity, null);
        var realEntityCollection = entityCollection as RelatedEnd;
        if (realEntityCollection != null && !realEntityCollection.IsLoaded)
        {
            realEntityCollection.Load();
        }

        Repeater1.DataSource = entityCollection;
        Repeater1.DataBind();
    }

    public override Control DataControl
    {
        get
        {
            return Repeater1;
        }
    }

}

by debugging, I can see the entityCollection always null, anything I've missed?

回答1:

Don't know what is ASP.NET Dynamic Data template. But in your models the ICollection<T> should add virtual prefix, for that you can get those model collection through lazyloading(ensure Configuration.LazyLoadingEnabled is not false in your DBContext). Maybe it's relate to your Dynamic Data template.



回答2:

I think the issue will be with your data model I have not used EF6 with DD as there are some issues for me (running Business logic in the on saving changes does not work with EF Data source) that aside all I can think is it is something to do with your model as the M2M field template works fine in EF5 and EF6 Database First mode.