GridView, Entity Data Source, RowDataBound ve Unable to cast object of type ‘System.Data.Objects.MaterializedDataRecord’ to type hatası

21 May
2011

GridView kontrolüne Entity Data Source ile data bind ettiniz. Sonra RowDataBound event’inde e.Row.DataItem‘i entity class a erişmek istediniz. O da ne, Unable to cast object of type ‘System.Data.Objects.MaterializedDataRecord’ to type ‘ProjectEntities.User’ diye bir hata aldınız. Çözümü aşağıda:

Önce Configure Entity Data Source ekranını açın ve orada EntityTypeFilter olarak erişmek istediğiniz class’ı seçin.

Daha sonra aşağıdaki extension method’u projenize ekleyin.

        public static TEntity GetItemObject<TEntity>(object dataItem)
            where TEntity : class
        {
            var entity = dataItem as TEntity;
            if (entity != null)
            {
                return entity;
            }
            var td = dataItem as ICustomTypeDescriptor;
            if (td != null)
            {
                return (TEntity)td.GetPropertyOwner(null);
            }
            return null;
        }

Artık RowDatabound eventi’nde dönüştürmeyi yapabilirsiniz.

        protected void grdUsers_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ProjectEntities.User user = GetItemObject<ProjectEntities.User>(e.Row.DataItem);
            }
        }
RowDataBound
RowDataBound
Be Sociable, Share!

Comment Form

You must be logged in to post a comment.

top