w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
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

Nhibernate throws Object of type 'System.Linq.EnumerableQuery`1[Entity]' cannot be converted to type 'System.Linq.IQueryable`1[System.Object[]]'
.AsQueryable() will wrap the given IQueryable from NH needlessly into a new Queryable but since NH will by default use object arrays as results and transform it later it will fail casting. Also Selecting the user into another User will prevent changetracking and is needless copying. repo.GetAll().Where(f => f.Id == id).FirstOrDefault(); should be enough or even better because of the sessioncache usage var user = session.Get<User>(id); if (user == null) // user with given Id does not exist

Categories : C#

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#

LINQ to Entities does not recognize the method 'System.Linq.IQueryable`
You could just select the Id and after it create your own anonymous object using linq to objects, for sample: var model = _db2.Persons.Select(x => x.Id) .ToList() // return int[] .Select((id, index) => new { rn = index + 1, col1 = id }) // return anonymous[] (with rn and col1) .AsEnumerable(); // get an IEnumerable (readonly collection) Problably this is happen because Entity Framework does not support this kind of query using linq as linq could do in memory, so, in this case, you could select just you need (id in your case) and execute it, using ToList() method to concretiz

Categories : C#

Complex Linq query errors "..Entities does not recognize the method.."
As the error clearly states, EF's query translator doesn't know what to do with ToString(). If that is a char, you can compare it to a character literal directly using single quotes.

Categories : Wcf

Cannot implicitly convert type 'System.Linq.IQueryable' to 'bool'
context.SomeTables.Where(p => p.FileName == System.IO.Path.GetFileName(file)) returns an IQueryable, not a bool. You need something that returns a bool, like context.SomeTables.Any(p => p.FileName == System.IO.Path.GetFileName(file)) as your condition for the if statement. See Also Enumerable.Any Method (IEnumerable)

Categories : C#

An item of type 'Attribute' cannot be constructed within a node of type 'Root
<xsl:template match="Inspection[not(@lossFormsVersion)]"> <xsl:copy> <xsl:attribute name="lossFormsVersion">07-25-2013-1-54</xsl:attribute> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> For 2nd xml, your template matches the element where you write the attribute to output. xsl:copy copies the ├Ćnspection node and the attribute writes to that.

Categories : Xml

Complex type mapping via linq to xml
You can access the elements directly by adding another '.Element'. I added a variable for better readability. var contacts = from c in xdoc.Element(mdpr + "Data") .Element(mdpr + "contactList") .Elements(mdpr + "contact") let contact = c let connection = contact.Element(mdpr + "connection") select new Contact { TransportCode = (string)contact.Element(mdpr + "TransportCode"), Name = (string)contact.Element(mdpr + "Name"), Connection = new Connection { status = (string)connection.Element(mdpr + "status"), startDate = (string) connection.Element(mdpr + "st

Categories : C#

Caching/compiling complex Linq query (Entity Framework)
Your premise is incorrect. Because you have a ToList call at the end of your query you are querying the database where you've indicated, to construct the list. You're not deferring execution any longer. That's why it takes so long. You aren't spending a long time constructing the query, it's taking a long time to go to the database and actually execute it. If it helps you can use the following method to do the pagination for you. It will defer fetching each page until you ask for the next one: public static IEnumerable<IEnumerable<T>> Paginate<T>( this IQueryable<T> query, int pagesize) { int pageNumber = 0; var page = query.Take(pagesize).ToList(); while (page.Any()) { yield return page; pageNumber++; page = query

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#

ObjectContext.GetObjectType(e.GetType()) not returning the entity type of the POCO entity
You are using the wrong ObjectContext. EF6 is not built on System.Data.Entity.dll. You need to use ObjectContext from EntityFramework.dll. It's actually not recommended to have a reference to System.Data.Entity.dll in your project at all if you are using EF6 to avoid situation like this. To fix your issue: remove the reference to System.Data.Entity.dll (just in case) replace System.Data.Objects.ObjectContext.GetObjectType(e.GetType()); with System.Data.Entity.Core.Objects.ObjectContext.GetObjectType(e.GetType())

Categories : C#

Entity Framework isn't getting the columns for Complex Type
@chiefGui I did not understand your question perfectly well, but seems when you click in "Get Column Information" button, you get no columns. If it's that the problem you can fix it by adding a command in you procedure. Put a command like this. ALTER PROC ProcName /* ([,parameters] ) */ AS BEGIN /* this command you make the difference */ SET FMTONLY OFF /* other code here */ END Put this in first line of inside of your procedure. Remove the procedure from EDMX, add again and try again the import. And you'll get all columns returned by your procedure. So de step by step will working well. If this is not the answer you want please add comment so I can help you. EDITED This happens because the EF try to getting columns headers without getting a result data. If your proce

Categories : C#

How to integrate a Linq to Entity query that queries multiple entities in a repository and send data to View?
how best to integrate a method which contains a query that queries multiple entities into the repository. Considering the relationship between User and Journey, you should decide which entity owns the relationship and use Aggregate Root to fetch data. The description of Aggregate Root at What's an Aggregate Root? would be helpful. Update: Entities public class User { public User() { this.Journeys = new List<Journey>(); } public int Id { get; set; } public virtual IList<Journey> Journeys { get; set; } } public class Journey { public Journey() { this.Users = new List<User>(); } public int Id { get; set; } public virtual IList<User> Users { get; set; } } Repositiories public class UserReposito

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#

Entity framework complex type multiple instances in one model?
With EF 6, Code First will prefix the column names with your Property name when you use multiple instances of same complex type, like PersonalAddress_Street BusinessAddress_Street ... and so on. You only need the mappings older versions of EF. The mapping option also allows you to replace these autogenerated names with something nicer. Also, I don't think this is the correct configuration code based on your models (typo maybe?): this.Property(t => t.PersonalAddress.Address.Street) // should be this.Property(t => t.PersonalAddress.Street)

Categories : C#

AutoMapping an Enum to an Entity Framework 5.0 complex type error
If you have problmes with complex type mapping, you can implement manual mapping based on AutoMapper: Mapper.CreateMap<PatternDto, PatternModel>().ConvertUsing(pattern => { if(pattern == null) return new PatternModel(); return new PatternModel { EmailPattern = pattern.EmailPattern, SmsPattern = pattern.SmsPattern }; }); Good luck!

Categories : Entity Framework

ASP.NET MVC with Entity Framework - Update/Save complex type property
As you mentioned, the problem occurs when more than one quantity has same Unit. To avoid adding same unit multiple time you can check if a unit is already in the db. If it exists then reuse the existing unit. if (q.Id == 0) { var unit=db.Units.FirstOrDefault(u=>u.Id==q.Unit.Id); if(unit!=null) q.Unit=unit; db.Quantities.Add(q); }

Categories : C#

Entity Framework 5 table-per-type update, change sub type but keep same base type
I don't have a good answer, but I can think of four "solutions" that are really workarounds: Don't use DBMS-computed values for your primary keys (if you already use natural keys, it's fine). Use DBMS-computed surrogate keys. Follow something like the state pattern. Do some evil voodoo with the object state manager. Update: There seems to be a popular consensus that trying isn't even worth it; most people thus simply use stored procedures instead to work around the problem. Changing Inherited Types in Entity Framework Entity Framework: Inheritance, change object type Changing the type of an (Entity Framework) entity that is part of an inheritance hierarchy Changing the type of an entity that is part of an inheritance hierarchy Using natural keys First, remember that the objects tr

Categories : Entity Framework

Getting an type conversion error while using linq in entity framework
try using Dim standard = (From s In db.Standards Where s.StandardId = CInt(ComboSelectStandardToEdit.SelectedValue) Select s) .FirstOrDefault txtStandardName.Text = standard.StandardName your Linq query currently is returing a projection which could contain multiple entries. By explicitly requesting the first object of the projection, you won't need to cast your standard before accessing it's value.

Categories : Sql Server

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 - How to use a variable of type List in Where clause
If you have a list of objects and you want to see if an particular object is in that list, then you do: myList.Contains(myObject); You're looking to see if your list contains your object. All your samples above seem to have this backwards. Going back to your original sample, try this: public List<Person> GetPeople() { // Get the list of codes that the user belongs to var userLocationCodes = repo.GetUserLocations().Select(i => i.LocationCode); // Do one query to see if the location is in your list of location codes var query = (from p in db.Person join t in db.TrespassedLocation on p.PersonId equals t.PersonId where userLocationCodes.Contains(t.SiteCode) select p); return query.ToList(); } However, some entity framework providers don't like .Contains

Categories : Linq

Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Linq.IQueryable'
When you apply the When clause you use the type (cust, sa) => new { customer = cust, advice = sa }. But after you change to new { cust_id = g.Key.cust_id, cust_code = g.Key.cust_code, cust_name = g.Key.cust_name } They are different types to compiler.

Categories : C#

Mongo/DataNucleus/JPA with embedded type query gives: Cannot find type of (part of) ... since symbol has no type; implicit variable?
FINE: Compilation of filter to be evaluated completely in-datastore was impossible : Invoke expression is not supported by this mapper so it is not currently implemented to convert JPQL "collField.contains(val)" (the equivalent of what you typed in for your query) into a MongoDB query, hence cant evaluate it in the datastore. Since you know what it needs converting into, you can easily enough get the code for the DataNucleus MongoDB plugin and find class QueryToMongoDBMapper and contribute support for that particular query.

Categories : Mongodb

Serialize complex type as simple type JSON
import this namespace System.Web.Script.Serialization; string SerializeObject() { var objs = new List<Test>() var objSerialized = new JavaScriptSerializer(); return objSerialized .Serialize(objs); } I use as example a List but you will use your object instead.

Categories : C#

Linq Query with dynamic type
You could either use reflection (not recommended) or just use the ternary operator: !(IsSqlServer ? row.Field<int?>("id").HasValue : row.Field<long?>("id").HasValue)

Categories : C#

The type String cannot be constructed
As your code sample, I'm assuming you are on a Controller and not a API Controller (from web api). Your api controller has a dependency on the constructor from HttpConfiguration. The container problably does not have this definition for this type and consequently does not know how to solve it and the string on the error message should come from this type as a dependency. I recommend you use the GlobalConfiguration static class and access the Configuration property to get a HttpConfiguration instance. You could abstract it in a property, for sample: // include this namespace using System.Web.Http; public class HelpController : Controller { // remove the constructors... // property protected static HttpConfiguration Configuration { get { return GlobalConfiguration

Categories : Asp Net Web Api

Can't get IEnumerable type using linq filtered query
Why your PostModel class object would be Equals string cat? Maybe you meant: data.PostTables.Where(Post => Post.CategoryName == cat) Even though you overrided Equals method on PostModel I think you should use line I meantioned above because it is more obvious. Also at the end of query you should call .ToList() method for initiating it. And you should dispose context after creating it in the method. public static IEnumerable<PostModel> GetPostData(string cat) { var data = new LinqClassDataContext(); var pm = data.PostTables.Where(post => post.CategoryName == cat) .Select(Post => new PostModel { PostID = (int)Post.PostI

Categories : Linq

C# - How to check if object of a type needs to be constructed?
The difficulty here is in the creationing the instances; it's quite easy to find out whether instances will be created on array allocation: just check default(T) value. But how can we create an instance manually? What if your class has, say, five constructors? In the code below, I create the instance if its class has a default constructor which is public and has no arguments. public static T[] CreateArray<T>(int size) { if (size < 0) throw new ArgumentOutOfRangeException("size"); T[] result = new T[size]; // You may put any special cases here, e.g. if you want empty strings instead of nulls // uncomment the exerp: //if (typeof(T) == typeof(String)) { // for (int i = 0; i < result.Length; ++i) // result[i] = (T) ((Object) ""); // // return result

Categories : C#

"The type LogWriter cannot be constructed" in web app in new AppDomain
You need to set the new AppDomain's configuration file so that Enterprise Library can be configured in the new AppDomain. You can do this using the AppDomainSetup.ConfigurationFile property: AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationName = "TestAppName"; setup.ApplicationBase = baseFolder; setup.PrivateBinPath = folder; setup.ShadowCopyFiles = "true"; setup.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;

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#

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 query issues with date type data
It looks like you have an DateTime that hasn't been set. The default value of a DateTime is "01/01/0001 00:00:00". // outputs the value of an empty DateTime: "01/01/0001 00:00:00" Console.WriteLine(default(DateTime)); Are you sure that the dateofjoin is assigned? I don't see it in you code.

Categories : Linq

Get Class and object type from linq list query
You need to separate the concepts of "the field" from "the value of that field for a particular instance". You want FieldInfo.GetValue, e.g. var monitoringClass = (SystemClass) field.GetValue(null); EDIT: I note that SystemMonitoringClass.Computer is actually declared to return a value of type SystemClass, not SystemMonitoringClass - so you may want to change your cast appropriately, as I have above.

Categories : C#

LINQ to Entities - Entity Framework
IEnumerable represents a sequence of elements which you enumerate one by one until you find the answer you need, so for example if I wanted all entities that had some property greater than 10, I'd need to go through each one in turn and return only those that matched. Pulling every row of a database table into memory in order to do this would not maybe be a great idea. IQueryable on the other hand represents a set of elements on which operations like filtering can be deferred to the underlying data source, so in the filtering case, if I were to implement IQueryable on top of a custom data source (or use LINQ to Entities!) then I could give the hard work of filtering / grouping etc to the data source (e.g. a database). The major downside of IQueryable is that implementing it is pretty har

Categories : C#

Entity Framework Code First Table-Per-Type Inheritance include base type
The answer was to remove the abstract keyword from the Base class (Person): FROM: public abstract class Person { public string FirstName { get; set; } public string LastName { get; set; } public Training Training { get; set; } } TO: public class Person { public string FirstName { get; set; } public string LastName { get; set; } public Training Training { get; set; } }

Categories : C#

Entity Framework Code First: Computed property of type Type causes ArgumentNullException on Update-Database
Use NotMappedAttribute: Denotes that a property or class should be excluded from database mapping.

Categories : C#

Capture Return Value of Method returning base type or derived type
Well, you can do if (ref instanceof B) { B r = (B)ref; } but fundamentally I think you have a modelling problem. Why do you have a factory (or similar) returning instances of A or B, and then have to determine what you've been given ? Perhaps you can have a method common to but implemented differently in both A and B, and call that, passing in your reference to the caller (originating) class. That way you can invoke a different method depending on both the type calling, and the type being called.

Categories : Java

error: a value of type "void *" cannot be assigned to an entity of type "float *"
What is happening here is that most likely you are inadvertently compiling your code as C++ code. In C++ (as opposed to C) void * is not implicitly convertible to other pointer types. It you intend to write your code in C, make sure you compile it as C. It you intend to write your code in C++, you will have to use explicit type conversion operators to convert void * pointers to other pointer types. The conversion to long * pointer type probably happens in other translation unit (i.e. other file), which is compiled as C. That is probably why it succeeds. Note that compilers can use C and C++ mode independently for each translation unit. Many compilers will choose between C and C++ based on file extension, compiling .c files as C and .cpp files as C++.

Categories : C

Do Entity Framework Provide Utility that convert DB Type To C# Type?
I dont know such a public method (I think there is none... it that may be accepted as answer) However, try to uncompile sqlmetal.exe, you can have a good idea of how default associations are implemented internally: In class LinqToSqlShared.Utility.DbTypeSystem (internal class) you can find the method: internal static Type GetClosestRuntimeType(SqlDbType sqlDbType) { switch (sqlDbType) { case SqlDbType.BigInt: return typeof(long); case SqlDbType.Binary: case SqlDbType.Image: case SqlDbType.Timestamp: case SqlDbType.VarBinary: return typeof(Binary); case SqlDbType.Bit: return typeof(bool); case SqlDbType.Char: case SqlDbType.NChar: case SqlDbType.NText: case SqlDbType.NVarChar: case SqlDbType.Text: case SqlDbType.

Categories : C#



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