w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Unable to create a constant value of type 'Anonymous type'. Only primitive types or enumeration types are supported in this context
The problem is the ToList() call on details. In EF, you can only refer to an IEnumerable inside a Query if that IEnumerable is of a simple type (e. g. int). However, you CAN refer to another IQueryable. Thus, dropping the ToList() call should make this work. EDIT: similarly, you should drop the ToList() call on ctx.CompanySettings. This will have the added advantage of executing only 1 query instead of 2. If you drop the ToList() on details, EF will generate something like: SELECT ... FROM RegisteredBikes rb JOIN ( /* this is your "details" IQueryable */ SELECT Serial, EmailAddress FROM BikeDetails WHERE ... ) bd ON rb.Serial = b.Serial JOIN CompanySettings cs ON ... WHERE ... EDIT: to do this across contexts, you'll need to bring the query into memory (e. g. b

Categories : C#

Unable to cast object of type 'System.Linq.OrderedEnumerable`2[***]' to type 'System.Collections.Generic.IEnumerable`1[***]'
You're trying to convert a collection of DirectoryToken to a collection of Token. This is called a covariant conversion, and it's only supported in .Net 4.0 or later. If you can't upgrade, you can call .Cast<Token>() to create a new IEnumerable<T> instance (actually an iterator) that casts each object to the desired type. Under no circumstances do you need an explicit cast operation.

Categories : C#

Unable to cast object of type to type 'System.Data.Objects.ObjectContext
Try the link for MSDN Article below solved my problem when I was going through the same tutorial. MSDN Article! Just change SchoolContext to SchoolEntities in the method SchoolContextEntityDataSource_ContextCreating() Best regards, Adit Malik

Categories : Entity Framework

Unable to cast object of type VB$AnonymousDelegate to type System.Func
"Function() to a Func" is not an implicit conversion precisely, but the normal assignation which Func expects (that is, a Function). You are not including the As Func(Of T, Boolean) bit in BoolFunc, what makes this function "anonymous" (you are not saying explicitly the returned type). Include this bit and it should work without any problem. That is, replace your BoolFunc with this one: Public Function BoolFunc(Of T)(ByVal bfunc As Func(Of Boolean, Boolean, Boolean), ByVal f1 As Func(Of T, Boolean), ByVal f2 As Func(Of T, Boolean)) As Func(Of T, Boolean) If f1 Is Nothing Then Return f2 If f2 Is Nothing Then Return f1 Return Function(param As T) bfunc(f1(param), f2(param)) End Function

Categories : Vb.Net

Unable to cast object of type 'WhereSelectListIterator` in LINQ
bw will be a sequence of BackgroundWorker items - so you can't cast from that sequence to a single item. There are a number of methods which will give you a single item, e.g. First FirstOrDefault Single SingleOrDefault Last LastOrDefault You should work out whether you should use one of those, or actually iterate over all the results of the query.

Categories : Dotnet

Does java create a new Object when a primitive type is passed to a method that expects a Wrapper of a primitive type?
Does the JVM create a new Integer when doing that? Not for the example you've given, no - because it's in the range [-128, 127]. If your example had been 157 instead, the answer would have been implementation-specific. From section 5.1.7 of the JLS: If the value p being boxed is true, false, a byte, or a char in the range u0000 to u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2. Ideally, boxing a given primitive value p, would always yield an identical reference. In practice, this may not be feasible using existing implementation techniques. The rules above are a pragmatic compromise. The final clause above requires that certain common values always be

Categories : Java

Unable to cast object of type 'System.Web.Security.SqlRoleProvider' to type 'WebMatrix.WebData.SimpleRoleProvider'
That's because SqlRoleProvider does not inherit SimpleRoleProvider. However, you can try using SimpleRoleProvider Constructor (RoleProvider): var roles = new SimpleRoleProvider(Roles.Provider);

Categories : Sql Server

Using weka in C#: Unable to cast object of type 'java.util.ArrayList' to type 'System.Collections.Generic.List`
I am answering my own question. I used this link to solve the problem I was facing. Thanks @SecretSquirrel(see the comments) and @Jon Iles (see the answer I've linked).

Categories : C#

Linq to Entities - "Unable to create a constant value of type 'System.Object'..."
I think it is the following line that causes the problems: Line = (p.ProdLine.Factory.Factory_No + '/' + p.ProdLine.ProdLine_No.ToString()) This is since it combines a query-result with a .NET method result. Maybe this will work. It delays the creation the of Line-variable-contents until after the query has been run. var query = (from p in Productions join t in MaterialTransactions on p.Prodn_ID equals t.Prodn_ID where p.WO_ID == 2345 orderby p.Date descending select new { Id = p.Prodn_ID, Date = p.Date, Line1 = p.ProdLine.Factory.Factory_No, Line2 = p.ProdLine.ProdLine_No, Qty = p.Qty, Wgt = (double)p.ActWgt, Speed = (double)p.ActSpeed, MaterialUsed = t.Material.Name }) .AsEnumerable() // This is where the db-stuff stops, and the in-memory stuff b

Categories : C#

Primitive type casting
All compound assignment operators not only performs the operation, but also cast automatically their result to the type of the left-hand side variable. So your += not only adds variables and assign the result - it also cast the result to the right type.

Categories : Java

Using Many to many with ef linq expression gave me "Unable to create a constant value of type (type)"
The Entity Framework can't translate the Contains(product) to SQL code. Your problem lies here: discount.Products.Contains(product) You should search the product by it's ProductID, which should be a primitive type. This is a know issue which is documented here: Referencing Non-Scalar Variables Not Supported : Referencing a non-scalar variables, such as an entity, in a query is not supported. When such a query executes, a NotSupportedException exception is thrown with a message that states "Unable to create a constant value of type EntityType. Only primitive types ('such as Int32, String, and Guid') are supported in this context."

Categories : Entity Framework

LINQ - "Unable to create constant value of type [type]"?
Try using LINQ 'Where In', this should solve your problem: var names = new string[] { "Alex", "Colin", "Danny", "Diego" }; var matches = from person in people where names.Contains(person.Firstname) select person; OR var matches = from person in people where person.Firstname == "Alex" || person.Firstname == "Colin" || person.Firstname == "Danny" || person.Firstname == "Diego" select person; http://blogs.msdn.com/b/alexj/archive/2009/03/26/tip-8-writing-where-in-style-queries-using-linq-to-entities.aspx

Categories : C#

If strings are nullable by default, why do i get Unable to cast object of type 'System.DBNull' to type 'System.String'.?
Because null != DBNull.Value. But you can check if it the value in the DataReader is null with the IsDbNull method: DestributionGroup = dr.IsDbNull("Destribution Group") ? "" : dr.GetString("Destribution Group");

Categories : C#

Unable to cast object of type 'System.Data.SqlClient.SqlDataReader' to type 'System.IConvertible'
It's exactly what the error says. You can't convert an SqlDataReader to a DateTime. If you want to query for just a single value, you should use: cmd2.ExecuteScalar(); If you are looking to retrieve a single value, I would suggest using TOP 1 in your query as well: SELECT TOP 1 DISTINCT loanUpdateDate Also note that ExecuteScalar() can return DbNull.Value if no value is found, so be sure to do a null check before trying to convert the value to anything.

Categories : C#

Unable to cast object of type 'System.Int32' to type 'System.Data.DataRowView'
Try to Direct Cast the value : (DirectCast(LbmCat.SelectedItem, DataRowView)("ID").ToString()) See it here. It may help

Categories : Vb.Net

Unable to cast object of type 'System.String[]' to type 'System.IConvertible'
Try this, weight is an array. Assuming you want to convert first element of array. string[] weight = txtProductOptn1.Text.Split(','); var Weight1 = Convert.ToInt32(weight[0]);

Categories : C#

Unable to cast object of type 'System.Int16' to type 'System.String'
This t.Field<string>("db_code").ToString() perhaps should be this: t.Field<short>("db_code").ToString() or equivalent t.Field<Int16>("db_code").ToString()

Categories : C#

Variable store function as primitive type or reference type?
The value of f2 is, like f1, a reference to the same function. You can use the fact that functions are objects to prove it : var f1 = function(){} var f2 = f1; f1.a = 3; console.log(f2.a); // logs 3 But as you can't change a function core, there is little practical use in knowing this, apart the fact you don't use much memory if you duplicate a function reference.

Categories : Javascript

C#.NET Error: Unable to cast object of type 'System.Data.DataTable' to type 'System.Data.DataSet'
It's because you're setting the DataSource to a DataTable: gvPartNumber.DataSource = dsgvPartNumber.Tables["partNumbers"]; not a DataSet. So, instead of this: DataSet dsgvPartNumberDelete = (DataSet)gvPartNumber.DataSource; do this: DataTable dsgvPartNumberDelete = (DataTable)gvPartNumber.DataSource; and then in the following lines you won't need accessors like .Tables[0]. It will already be a DataTable and thus more direct to access anyway. This modification would of course have to be replicated to all of your methods where you're trying to cast the DataSource as a DataSet.

Categories : C#

How Generics allows strong type checking for Type Casting errors during Compile Time
JPA makes use of generics in TypedQuerys to ensure that the expected type is returned. If you ask for a Customer, the type system knows to treat the results of the query as Customer objects and not as a plain Object you have to cast yourself, and if you use the Criteria API, it can also verify that your query parameters refer to valid attributes of the Customer class.

Categories : Java

Does type erasure of Java Generics cause full type casting?
The type-checking is done at compile-time. If you do this: List<Cheesecake> list = new ArrayList<Cheesecake>(); then the generic types can be checked at compile-time. This erases to: List list = new ArrayList(); which is no different to any other up-cast (e.g. Object o = new Integer(5);).

Categories : Java

MVC LinQ IQueryable Anonymous type handling
here your dynamic type only inside the scope of the TestMethod. You better create new class and return that class to the caller. public class testClass{ public IQueryable<MyClass> TestMethod(){ return from m in db.testTable join n in db.testTable2 on m.ID equals n.ID into tabA from a in tabA join o in db.testTable3 on m.UserID equals o.ID select new MyClass{ .................}; } } If you need to return anonymous type then check this Can't return anonymous type from method? Really?

Categories : C#

.net linq winforms cannot convert anonymous type
Your code projects the results into a sequence of anonymous type instances new { a, b }, and you are trying to use that list as a list of something else. Project the results into the proper named type instead. For example, one solution might be var query = (from a in pamsEntities.appraisals where a.emp_no == employeeId join b in pamsEntities.AppraisalReadinesses on a.AppraisalReadiness.Code equals b.Code select Tuple.Create(a, b)).ToList(); This will get you a list of Tuple<T1, T2> where T1 is the type of a and T2 is the type of b. You can of course create your own custom type instead: class MyType { // I am guessing about the type names here, based on your query Appraisal Appraisal; { get; set; } AppraisalReadines

Categories : Dotnet

Oracle ODAC error setting up website in IIS: type A cannot be cast to type B?
Looks like an old version of the data access DLL is installed in the GAC. Does the DLL in c:windowsmicrosoft.net... exist? If not, you may have to provide a copy of it in a bin folder and update your config to use the DLL in the bin. This assumes you want to use the new version and not the old one in the GAC.

Categories : C#

Can we Convert Anonymous Type to List using Linq to entity in C#?
Just use the actual concrete type instead of an anonymous one: select new Material { ID = c2.ID, MaterialParentID = c2.MaterialParentID, Name = c2.Name, ParentName = c1.Name }

Categories : C#

Linq anonymous type with list object property
You need to take the collection of desks from the data model, convert each one to a DeskViewModel, and convert the resulting sequence to a List<T>. That would look something like p.Desks.Select(d => new DeskViewModel { ... }).ToList()

Categories : C#

How to cast a string value to some specific type when we have only Class object of the type?
According to what you describe, if you have: String var = "variable"; Class<?> type = Class.forName("your_class");// Your type Object o = type.cast(var); Now 3 things can happen: o should be of your_class type If var is null, o will be null or ClassCastException will be thrown

Categories : Java

How to merge LINQ querys of lambdas which return of anonymous type?
To use the Union method, the collections must have the same type. In order for two anonymous types to be considered the same, they must have exactly the same members with exactly the same types. Try this: var quartEst = Quarterly_estimates ... .Select (q => new { Tick = q.Ticker, // renamed ticker to Tick Quarter = q.Quarter, Year = q.Yyyy, Eps = q.Eps}) ... var quartAct = Quarterlies .Select (q => new { Tick = q.Ticker, Quarter = q.Quarter, Year = q.Yyyy, Eps = q.Eps_adj}) ... var quartComb = quartEst.Union(quartAct);

Categories : C#

Building a dynamic anonymous type Select statement using Linq
The answer to your question relies on anonymous types. The following code is what you can use: var result = list.AsQueryable().Cast<Info>().Select(x => new { AccountId = x.AccountId, Name = x.Name }); Between the brackets that follow the new keyword in the select statement, you are creating an anonymous type that will have two implicitly typed read-only fields (AccountId and Name). Hope this helps! I would like to post this quote from the linked (no pun intended) article: Anonymous types typically are used in the select clause of a query expression to return a subset of the properties from each object in the source sequence. For more information about queries, see LINQ Query Expressions (C# Programming Guide).

Categories : Linq

Linq call using anonymous/dynamic type does work in view
In your first example, you're getting a List<whatever s is>, in your second example, you're getting a List<object>. And 'object' does not contain a definition for 'No_'

Categories : Asp Net

LINQ - Select anonymous type which based on a collection property
You can't, unless you know the number of items in the list at compile time. The idea of anonymous types is that they're statically typed. The compiler knows, at compile time, what all of the properties and their types are. You can't use one if you don't know that information. If you know that there are, for example, always two items, then you can do something like: return data.Select(x => new { x.DeviceID, x.DeviceName, x.HasChild, x.KwhImport, x.KwhExport, x.MaxDmd, x.ParentID, Tarrifs1 = x.Tarrifs[0], Tarrifs2 = x.Tarrifs[1], }).ToList();

Categories : C#

.NET LINQ to Entities base where clause for generic Type
I think LINQ to Entities does not know how to match the cast operator to SQL request. As a suggestion, you could try something like that: IEnumerable<IPublishable> ReadPublishable(Expression<Func<DomainModelType, bool>> condition) The expression act as a predicate. So you pass to the ReadPublishable function a predicate that filters the IPublishable objects you need. I tried successfully but only on simple predicates so, I do not know whether that works if you make use of "is" or "as" operators.

Categories : C#

Best way to avoid "The specified type member '*' is not supported in LINQ to Entities"
If you don't want to load the entities into memory and if you can't reproduce the logic of your Income property in SQL to create a calculated - and then mapped - database column, there isn't much you can do. The only option I would see is reducing the amount of loaded data as much as possible to the minimum that is required to perform the calculation - for example by creating a helper property ... public class IncomeCalculationData { public int X { get; set; } public double Y { get; set; } //... } ... using a projection that only loads those required properties instead of full entities ... var incomeCalculationDataList = from refs in entities.ReferralSet where refs.ReferralSince >= fromDate && (refs.ReferralTill ?? DateTime.Today) <= toDate

Categories : C#

How to cast to an object to a type when type is known during runtime?
Unfortunately, it's not just that its the "same class in a different namespace"... basically, you have 2 classes. They are completely different classes, because of the auto generated code. As far as the .Net Runtime is concerned, they might as well be as different as "int" and "string". They probably even hail from different assemblies. I've had a similar issue as well - and at this point, probably the easiest thing you can do is make your own generic converter method that will read the public properties from the one type, and populate them on the another type. This can be done because you PROMISE that the two classes look identical :)

Categories : C#

LINQ throwing TypeAs expression with input of type 1 and check of type 2 is not supported
Unfortunately, you're going to have to do this dynamically. Generics (combined with Entity Framework's apparent fear of typecasting) won't allow you to write the code you want in a static manner. So try this instead: using System.Linq.Expressions; public static Expression<Func<TEntity, bool>> DefaultFilter<TEntity>() where TEntity : IEntity { if (typeof(SoftDeleteEntity).IsAssignableFrom(typeof(TEntity))) return DefaultFilterSoftDelete<TEntity>(); else return x => true; } public static Expression<Func<TEntity, bool>> DefaultFilterSoftDelete<TEntity>() where TEntity : IEntity { var parameterExpression = Expression.Parameter(typeof(TEntity)); var propertyExpression = Expression.Property(parameterExpression, "

Categories : C#

Error: The entity or complex type cannot be constructed in a LINQ to Entities query
You can't project onto a mapped entity (see this answer). However, you can do a couple of things: 1) Select an anonymous type instead of entity like: var query = (from sd in db.site_desquesnoticias join sn in db.site_noticias on sd.IDNoticia equals sn.IDNoticia where sn.Destaque == 1 select new { CorpoNoticia = sn.CorpoNoticia, TituloNoticia = sn.TituloNoticia }).ToList(); 2) Invert your query to select the site_noticias directly. That depends on the query and the data that you would like to retrieve. For example, you can have a look if the following will work and give you the data that you need: var query = (from sd in db.site_desquesnoticias

Categories : Asp Net Mvc

System.InvalidCastException: Unable to cast object of type
_Bots.Values is a collection of virtualBot and your code should be foreach (virtualBot roomBot in _Bots.Values) { if (roomBot.goalX == -1) continue;

Categories : C#

Type casting using type parameter
That's what a ClassTag if for: import reflect.ClassTag def convert[T : ClassTag](key: String): Option[T] = { val ct = implicitly[ClassTag[T]] someJavaMethod(key) match { case ct(x) => Some(x) case _ => None } } It can be used as an extractor to test and cast to the proper type at the same time. Example: scala> def someJavaMethod(s: String): AnyRef = "e" someJavaMethod: (s: String)AnyRef [...] scala> convert[Int]("key") res4: Option[Int] = None scala> convert[String]("key") res5: Option[String] = Some(e) Edit: note however that a ClassTag does not automatically unbox boxed primitives. So, for example, convert[Int]("a") would never work, because the java method returns AnyRef, it would have to be convert[java.lang.Integer]("a"), and so on for other pri

Categories : Scala

Sqlite database unable to delete objects, failing with message "Cannot store type: "
Rather than use: public int DeleteItem<T>(int id) where T : IBusinessEntity, new() { lock (locker) { #if NETFX_CORE return Delete(new T() { ID = id }); #else return Delete<T> (new T () { ID = id }); #endif } } Use this instead: public int Delete(object objectToDelete) { var map = GetMapping(objectToDelete.GetType()); var pk = map.PK; if (pk == null) { throw new NotSupportedException("Cannot delete " + map.TableName + ": it has no PK"); } var q = string.Format("delete from "{0}" where "{1}" = ?", map.TableName, pk.Name); return Execute(q, pk.GetValue(objectToDelete)); }

Categories : Sqlite

C Casting a variable of type double to a variable of type char when freeing memory
I have to agree with you - that code is a bit weird. There's no reason the author couldn't have used void ** just as easily. In addition, the if (*ptr != NULL) check is unnecessary, since free(NULL) is perfectly legal. The ; characters after the braces aren't necessary either. A simpler version might look like this: static void free_and_null(void **ptr) { free(*ptr); *ptr = NULL; } The reason this function exists at all is to make sure that freed pointers are set to NULL, which is helpful for detecting use-after-free bugs and avoiding double-free bugs entirely. Edit: As StarPilot suggests below, it's probably a good idea to check that ptr itself isn't NULL: static void free_and_null(void **ptr) { if (ptr) { free(*ptr); *ptr = NULL; } }

Categories : C



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.