locked
Explicit construction of entity type '###' in query is not allowed.

    Question

  • What used to work in pre BETA 2/RTM does not work anymore. When accessing an EntitySet's Count property i get this:

    Explicit construction of entity type 'SmartFile.Data.FileData' in query is not allowed.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.NotSupportedException: Explicit construction of entity type 'SmartFile.Data.FileData' in query is not allowed.

    Source Error:

    Line 96:                     break;
    Line 97: case "program":
    Line 98: dataItemCount = ControlFile.DataItems.Count;
    Line 99: break;
    Line 100: case "location":

    Source File: c:\SmartFile Cc\SmartFile.Web\includes\controls\ControlFILE.ascx.cs    Line: 98

    Stack Trace:

    [NotSupportedException: Explicit construction of entity type 'SmartFile.Data.FileData' in query is not allowed.]
    System.Data.Linq.SqlClient.QueryConverter.VisitMemberInit(MemberInitExpression init) +714
    System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node) +209
    System.Data.Linq.SqlClient.QueryConverter.VisitSelect(Expression sequence, LambdaExpression selector) +163
    System.Data.Linq.SqlClient.QueryConverter.VisitSequenceOperatorCall(MethodCallExpression mc) +1036
    System.Data.Linq.SqlClient.QueryConverter.VisitMethodCall(MethodCallExpression mc) +82
    System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node) +935
    System.Data.Linq.SqlClient.QueryConverter.ConvertOuter(Expression node) +97
    System.Data.Linq.SqlClient.SqlProvider.BuildQuery(Expression query, SqlNodeAnnotations annotations) +416
    System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +443
    System.Data.Linq.DataQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +92
    SmartFile.Data.AccessibleControlFile.get_DataItems() +8142
    SmartFile.Web.includes_controls_ControlFILE.CreateFile() in c:\SmartFile Cc\SmartFile.Web\includes\controls\ControlFILE.ascx.cs:98
    SmartFile.Web.includes_controls_ControlFILE.Page_Load(Object sender, EventArgs e) in c:\SmartFile Cc\SmartFile.Web\includes\controls\ControlFILE.ascx.cs:33
    System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15
    System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33
    System.Web.UI.Control.OnLoad(EventArgs e) +99
    System.Web.UI.Control.LoadRecursive() +47
    System.Web.UI.Control.LoadRecursive() +131
    System.Web.UI.Control.LoadRecursive() +131
    System.Web.UI.Control.LoadRecursive() +131
    System.Web.UI.Control.LoadRecursive() +131
    System.Web.UI.Control.LoadRecursive() +131
    System.Web.UI.Control.LoadRecursive() +131
    System.Web.UI.Control.LoadRecursive() +131
    System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436

    My datacontext is extended as so:

        public partial class AccessibleControlFile
        {
            protected EntitySet<FileData> _dataItems;
            ///    <summary>
            ///    Returns all data items for control file
            ///    </summary>
            public EntitySet<FileData> DataItems
            {
                get
                {
                    _dataItems = new EntitySet<FileData>(onAddItem, onRemoveItem);

                    IEnumerable<FileData> items = LinqUtil.GlobalDb.sp_GetControlFileData((Guid)this.GUID);

                    foreach (var u in items)
                        _dataItems.Add(u);

                    return _dataItems;
                }
               
            }

    Any help is appreciated Smile.. 

    Cheers,
     -Kory
    Tuesday, November 27, 2007 11:12 PM

Answers

  • This check was added because it was supposed to be there from the beginning and was missing.  Constructing entity instances manually as a projection pollutes the cache with potentially malformed objects, leading to confused programmers and lots of bug reports for us. In addition, it is ambiguous whether projected entities should be in the cache or changed tracked at all. The usage pattern for entities is that they are created outside of queries and inserted into tables via the DataContext and then later retrieved via queries, never created by queries.

    Thursday, November 29, 2007 5:06 AM

All replies

  • What's in sp_GetControlFileData function?  Was this generated via a tool to execute a stored procedure or is it a function you wrote?   It's returning a query object (evident from the callstack) which is not what stored proc's normally do.

     

     

    Wednesday, November 28, 2007 12:12 AM
  • It was generated when i added the stored proc to the dbml.. the same error is thrown when i try the following code as well:

    public partial class AccessibleControlFile
        {
            protected EntitySet<FileData> _dataItems;
            ///    <summary>
            ///    Returns all data items for control file
            ///    </summary>
            public EntitySet<FileData> DataItems
            {
                get
                {
                    _dataItems = new EntitySet<FileData>(onAddItem, onRemoveItem);

                    var items = from i in LinqUtil.GlobalDb.ControlFileDatas
                                join ui in LinqUtil.GlobalDb.ControlFileDataJOINs on i.GUID equals ui.ControlFileDataGUID
                                where ui.ControlFileGUID == (Guid)this.GUID
                                orderby ui.PositionNumber ascending
                                orderby ui.Grouping ascending
                                select new FileData
                                {
                                    BitValue = (bool)i.BitValue,
                                    CurrencyValue = (decimal)i.CurrencyValue,
                                    DateValue = (DateTime)i.DateValue,
                                    DecimalValue = (decimal)i.DecimalValue,
                                    EffectiveEnd = (DateTime)i.EffectiveEnd,
                                    EffectiveStart = (DateTime)i.EffectiveStart,
                                    Grouping = (int)ui.Grouping,
                                    GUID = (Guid)i.GUID,
                                    IntValue = (int)i.IntValue,
                                    ItemCODE = i.ItemCODE,
                                    JoinTypeCODE = ui.TypeCODE,
                                    Name = i.Name,
                                    PositionNumber = (int)ui.PositionNumber,
                                    Required = (bool)i.Required,
                                    Sensitive = (bool)i.Sensitive,
                                    StringValue = i.StringValue,
                                    TextValue = i.TextValue,
                                    TypeCODE = i.TypeCODE
                                };
                    foreach (var u in items)
                        _dataItems.Add(u);

                    return _dataItems;
                }
            }
    Wednesday, November 28, 2007 4:18 AM
  • I am having a similar issue...

    I wrote the following in VS 2008 Beta 2 and it worked like a champ:

     

    public IList<Profile.DataTypes.tUser> ListUsers(Guid pCompanyUUID)

    {

    var query = (from u in _userContext.tUser

    where u.CompanyUUID.Equals(pCompanyUUID) && u.IsDeleted == false

    select new Profile.DataTypes.tUser

    {

    FirstName = u.FirstName,

    LastName = u.LastName,

    CompanyUUID = u.CompanyUUID,

    UserUUID = u.UserUUID,

    UserID = u.UserID

    });

    return query.ToList();

    }

     

    Now in the RTM version... I get the following error:

     

    Explicit construction of entity type 'Profile.DataTypes.tUser' in query is not allowed.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.NotSupportedException: Explicit construction of entity type 'Profile.DataTypes.tUser' in query is not allowed.

    Source Error:

    Line 39: 			query = this.GetSummaryQuery()
    Line 40: 				.Where(u => u.CompanyUUID.Equals(pCompanyUUID));
    Line 41: 			return query.ToList();
    Line 42: 		}
    Line 43: 

    Source File: C:\Sandboxes\Profile\Profile\Profile.Business\User.cs    Line: 41

    Stack Trace:

    [NotSupportedException: Explicit construction of entity type 'Profile.DataTypes.tUser' in query is not allowed.]
       System.Data.Linq.SqlClient.QueryConverter.VisitMemberInit(MemberInitExpression init) +716
       System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node) +206
       System.Data.Linq.SqlClient.QueryConverter.VisitSelect(Expression sequence, LambdaExpression selector) +163
       System.Data.Linq.SqlClient.QueryConverter.VisitSequenceOperatorCall(MethodCallExpression mc) +1120
       System.Data.Linq.SqlClient.QueryConverter.VisitMethodCall(MethodCallExpression mc) +80
       System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node) +921
       System.Data.Linq.SqlClient.QueryConverter.VisitWhere(Expression sequence, LambdaExpression predicate) +23
       System.Data.Linq.SqlClient.QueryConverter.VisitSequenceOperatorCall(MethodCallExpression mc) +3659
       System.Data.Linq.SqlClient.QueryConverter.VisitMethodCall(MethodCallExpression mc) +80
       System.Data.Linq.SqlClient.QueryConverter.VisitInner(Expression node) +921
       System.Data.Linq.SqlClient.QueryConverter.ConvertOuter(Expression node) +94
       System.Data.Linq.SqlClient.SqlProvider.BuildQuery(Expression query, SqlNodeAnnotations annotations) +418
       System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +444
       System.Data.Linq.DataQuery`1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +93
       System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +369
       System.Linq.Enumerable.ToList(IEnumerable`1 source) +54
       Profile.Business.User.ListUsers(Guid pCompanyUUID) in C:\Sandboxes\Profile\Profile\Profile.Business\User.cs:41
       Profile.Facade.UserManager.ListUsers(Guid pCompanyUUID) in C:\Sandboxes\Profile\Profile\Procuri.Facade\UserManager.cs:11
       ProfileWeb._Default.ListUsers() in C:\Sandboxes\Profile\Profile\ProfileWeb\Default.aspx.cs:55
       ProfileWeb._Default.Page_Load(Object sender, EventArgs e) in C:\Sandboxes\Profile\Profile\ProfileWeb\Default.aspx.cs:25
       System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15
       System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +33
       System.Web.UI.Control.OnLoad(EventArgs e) +99
       System.Web.UI.Control.LoadRecursive() +47
       System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1436
    

    Thursday, November 29, 2007 1:13 AM
  • If you take a look at System.Data.Linq.SqlClient.QueryConverter.VisitMemberInit from the RTM release in Reflector there is a check to see if the MetaType.IsEntity is true and if so then it throws an error

     

    If you take a look at this same method from the Beta2 release you will see that this check is not done.

    So clearly this creation of an "Entity" object within a "query" is totally allowed.

     

    Now why on earth would you go and add that check?

    Is this to limit the overhead of tracking the Entity or prevent "thrashing" the cached object in memory?

     

    I can understand if this check was added for those reasons but I can't understand why you wouldn't add a property or an expression which would allow for this to occur.

     

    What is really silly is that I can create a new class which inherits from the Entity and everything works like a champ. I guess what I am really saying is that I cannot believe that you are being forced to create a new class to perform this type of projection. Not that it is a huge deal but... introducing the DataContext and then an arbitrary class...

     

    Thursday, November 29, 2007 3:14 AM
  • This check was added because it was supposed to be there from the beginning and was missing.  Constructing entity instances manually as a projection pollutes the cache with potentially malformed objects, leading to confused programmers and lots of bug reports for us. In addition, it is ambiguous whether projected entities should be in the cache or changed tracked at all. The usage pattern for entities is that they are created outside of queries and inserted into tables via the DataContext and then later retrieved via queries, never created by queries.

    Thursday, November 29, 2007 5:06 AM
  • Thanks... Sorry about that.

    I had forgotten that if there are Primary Keys defined for a "Table" class in your DataContext then the "Table" class is treated like an Entity. If no keys are defined then it is simply a PONO

     

    Once I removed the Primary Key from the tUser class... everything worked liked it should of.

     

    Thursday, November 29, 2007 4:37 PM
  • The only problem is that once you remove a primary key, then you can no longer insert into the table.  In order to insert, the table needs to have a primary key defined.  I am not sure if you are ever going to have to do that, but it is causing me some strife right now. 

    Any work-around for the scenario where you want to insert into a table without a primary key?

    Thursday, November 13, 2008 2:02 PM
  • "leading to confused programmers and lots of bug reports for us."

    YOU HAVE GOT TO BE KIDDING ME!!! I'm not using the cache, object tracking, nor deffered loading. Data context are worthless other than short-lived queries (i.e. in a Using pattern). We programmers have to be protected?!?!?! How about protecting us from stupidity such as notions like this!

    Once again Microsoft can't think past applications bigger than Northwind...

    • Proposed as answer by werasdg Friday, December 17, 2010 9:31 AM
    Wednesday, October 13, 2010 12:27 AM