TPH EF6.0: Cannot calculate the value of expression - c#

I have 3 classes inherited from an abstract base class:
abstract class PortTaskStep{
public Guid TaskID { get; set; }
[ForeignKey("TaskID")]
public virtual PortChangeTask PortChangeTask { get; set; }
public virtual String CompleteStep() { return string.Empty;}
}
class PortTaskStep_Add:TaskStep{}
class PortTaskStep_Modify:TaskStep{}
class PortTaskStep_Delete:TaskStep{}
public class HncNetScanContext : DbContext
{
public DbSet<PortTaskStep> PortTaskSteps { get; set; }
}
When I try to get data from table 'PortTaskSteps', the query returns :
cannot calculate the value of the expression
Some more details:
public class PortChangeTask{
public ICollection<PortTaskStep> PortTaskSteps { get; set; }
public Boolean CompleteTask(){
foreach (var portTaskStep in PortTaskSteps)
{
portTaskStep.CompleteStep();
}
}
}
The Domain assembly contains the classes mentioned above are referenced by a web project and a web site. And when I debug the function in the web site, everything goes well.However, when I debug the same function in the web project, the results is null.
The Snapshot
For another scene tested in the Web Project:
As shown in the Snapshot, I try to get "PortTaskSteps". And the result is null. However, after I uncomment the "textQuery", the result is a list of PortTaskStep.
The Snapshot
I think something is going wrong in webconfig or environment of the Web Project, however, I cannot figure out the point...:(
How can I resolve the problem?
Thanks!

Perhaps the right translation might be "Could not evaluate expression". If so, then most likely it's the problem with Visual Studio. Try to delete all your breakpoints from solution and reinsert them. If that doesn't help you, check this link: Visual Studio 2013 'Could not evaluate Expression' Debugger Abnormality.
If the problem for you appears always on both retrieving data and trying to see it in the debug mode then you might want to check your configuration (maybe you've missed mapping or something important for this table).

Related

Visual studio for Mac looks into different class than referenced

After accidentally hitting rename of my skv_match class to skv_player class I have issue with my ReadMatches method. The Visual studio keeps telling me, there is no definition of methods in class skv_player when I use class skv_match instead (after I renamed the class back to skv_match).
I am desperate and don't know if I am doing something wrong or Visual studio for Mac is. Does anybody know how to solve this or did I miss something in the code?
I tried to restart the app and laptop, rebuild and clean project. I also tried deleting the figuring classes, creating them again and pasting the original content in them.
public string ReadMatches()
{
var matches = _context.skv_match.AsNoTracking();
StringBuilder sb = new StringBuilder();
if (matches == null)
{
return "No matches found";
}
else
{
foreach (var skv_match in matches)
{
sb.Append($"Match id: {skv_match.id }\r\n");
sb.Append($"Match results: {skv_match.home_team}");
sb.Append($"{skv_match.home_score }:");
sb.Append($"{skv_match.visitor_score } ");
sb.Append($" {skv_match.visitor_team }\r\n");
}
}
return sb.ToString();
}
public class skv_match
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.None)]
public int id { get; set; }
public string home_team { get; set; }
public string visitor_team { get; set; }
public int home_score { get; set; }
public int visitor_score { get; set; }
}
I get error: "'skv_player' does not contain a definition for 'home_team' and no accessible extension method 'home_team' accepting a first argument of type 'skv_player' could be found (are you missing a using directive or an assembly reference?)" and same for other methods
I expect the app to just take this without any errors, yet I get error that class I am not referencing misses methods. Before I accidentally hit rename the class everything worked just fine.
Ok my apologies to everyone who took time trying to help me. There was issue in Entity framework DbContext. I don't know if I was just tiredly stupid, or mentioned missclick changed it.
For anyone trying to solve this issue, try Right click on the declaration and "Go to declaration". It will point you to the part where you define it.
To be specific, I clicked on part skv_match at var matches = _context.skv_match.AsNoTracking();

Class property says "File not Found" ... before even being initialized?

I am having the weirdest problem right now ...
I am working on a program that tries to instantiate types (DbContext derivatives) from another project. Because the DbContexts don't simply accept standard parameters but only interfaces from that other projects I had to take some of the other project's assemblies and reference them so I could create dummy-types that implement the interfaces.
The main one is this:
class ContextConfigurationDummy:IContextConfiguration
{
#region privates
private ILogger GetLoggerDummy() => new LoggerDummy();
private ITenantSchemaResolver GetSchemaResolverDummy() => new SchemaResolverDummy();
private CultureInfo GetUserCulture() => new CultureInfo("en-US");
private DatabaseMetadata GetDbMetadata() => new DatabaseMetadata();
private IEntityValidatorFactory GetValidatorFactory() => new ValidatorFactoryDummy();
#endregion
public DbConnection GetDbConnection() => new SqlConnection(#"[insert connection string]");
public RuminantDummy GetRuminant() => new RuminantDummy();
public Func<CultureInfo> UserCulture { get; set; }
public Func<DbConnection> Connection { get; set; }
public Func<IDatabaseMappingRuminant> Ruminant { get; set; }
public Func<DatabaseMetadata> DatabaseMetadata { get; set; }
public IEntityValidatorFactory ValidatorFactory { get; set; }
public Func<ITenantSchemaResolver> TenantSchemaResolver { get; set; }
public Func<ILogger> Logger { get; set; }
public ContextConfigurationDummy()
{
UserCulture = GetUserCulture;
Connection = GetDbConnection;
Ruminant = GetRuminant;
DatabaseMetadata = GetDbMetadata;
ValidatorFactory = GetValidatorFactory();
TenantSchemaResolver = GetSchemaResolverDummy;
Logger = GetLoggerDummy;
}
}
The original interface is this:
public interface IContextConfiguration
{
Func<CultureInfo> UserCulture { get; set; }
Func<DbConnection> Connection { get; set; }
Func<IDatabaseMappingRuminant> Ruminant { get; set; }
Func<DatabaseMetadata> DatabaseMetadata { get; set; }
IEntityValidatorFactory ValidatorFactory { get; set; }
Func<ITenantSchemaResolver> TenantSchemaResolver { get; set; }
Func<ILogger> Logger { get; set; }
}
Everything was working just fine, I didn't look at that part of the code for a while, did quite a few changes to the rest (including to the project itself to adapt it for continuous integration), when I was done I started testing again and, when calling the constructor of ContextConfigurationDummy, I was faced with this:
Note how the debugger has not even tried to evaluate it yet! A "normal" error would be that the value is null and after it tries to evaluate it there would be some kind of exception. Not here. There isn't even any file being loaded in this class. Same error for all the following fields
I figured I had to have broken something while working on the project structure, so I remade the entire project, took only the code, re-referenced the assemblies, left everything at default ... and had the exact same error again. So, it has to be the code right?
Well, I reverted to an old commit through git, ran the program, everything working as it should. Great. Checked the code - the relevant parts are exactly the same, except for the Namespaces which were slightly adapted. So, not the code either?
I went back to my current commit and after trying different kinds of ways to reference the external assemblies I tried something else once again: Just for lulz I went into my Main, the Start of the program and tried to instantiate the class with exactly the same line I used to originally instantiate it: var dummy = new ContextConfigurationDummy();
It works. Everything as expected, my class just instantiates normally.
But as if this wasn't weird enough, I'll do you one better:
After calling the method in the main I kept the program running. I got back to the spot where I originally called new ContextConfigurationDummy(). Back into the constructor and ... it works there as well. Took the line out the main - doesn't work. Back in - works again.
I'm beyond stumped, please help. (and don't tell me to clean my solution, I've done so a hundred times and literally remade the entire thing) .
I'm effectively comibining answers from my own experiences and some google-fu here but.
.NET Version
Make sure you're using the same .NET version. I've had it where I've created a new project with an old .NET version and it's screwed me completely with the same issue.
Assembly Names
Make sure none of your dlls share the same name with the assembly you're bringing in. If you have two MyAssembly.dlls it could be looking for the wrong one / version. Additionally if you've updated the other project at some point, check that all your references are using the same version of a brought in dll.
Nuget Packages
Have you updated any Nuget packages in your project that are required by the other assembly also? (I've had this many times with my unit tests) if so you'll either need to update the other projects nuget packages to the same verison, or possibly add an App.Config file to tell it to use the newer version.
I've never had the same assembly names issue, but I've had the nuget package issue and the .net version issue quite a few times (It's something you just don't think about)

Error creating MVC 4 controller

I'm getting an error "Unable to retrieve Metadata for "TeamAssignment.Models.Test. Unable to cast object of type "System.Data.Entity.Core.Objects.ObjectContext" to type "System.Data.Objects.ObjectContext."
This is happening whenever I try to create a controller with action/views with the code first entity framework. I'm trying it with a simple test class that's not related to my project and even that is not getting through.
namespace TeamAssignment.Models
{
public class Test
{
[Key]
public int id { get; set; }
public string test { get; set; }
}
public class testDBContext : DbContext
{
public DbSet<Test> testing { get; set; }
}
}
Am I being retarded here or is something wrong with my overall program? I was having some issues with TFS earlier and I'm trying to determine if its related to that.
Sounds like you recently upgraded to EF6.
Unfortunately the MVC 4 scaffolding tools are not compatible with EF6 and there's nothing you can do except upgrade to MVC5 (if possible).

Dealing with Object Graphs - Web API

I recently encountered a (hopefully) small issue when toying around with a Web API project that involves returning object graphs so that they can be read as JSON.
Example of Task Object (generated through EF) :
//A Task Object (Parent) can consist of many Activities (Child Objects)
public partial class Task
{
public Task()
{
this.Activities = new HashSet<Activity>();
}
public int TaskId { get; set; }
public string TaskSummary { get; set; }
public string TaskDetail { get; set; }
public virtual ICollection<Activity> Activities { get; set; }
}
within my ApiController, I am requested a specific Task (by Id) along with all of it's associated Activities, via:
Example of Single Task Request
//Simple example of pulling an object along with the associated activities.
return repository.Single(t => t.Id == id).Include("Activities");
Everything appears to be working fine - however when I attempt to navigate to a URL to access this, such as /api/tasks/1, the method executes as it should, but no object is returned (just a simple cannot find that page).
If I request an Task that contains no activities - everything works as expected and it returns the proper JSON object with Activities : [].
I'm sure there are many way to tackle this issue - I just thought I would get some insight as to what people consider the best method of handling this.
Considered Methods (so far):
Using an alternative JSON Parser (such as Newtonsoft.JSON) which fixed the issue but appended $id and $refs throughout the return data, which could make parsing for Knockout difficult I believe.
Using projection and leveraging anonymous types to return the data. (Untested so far)
Removing the Include entirely and simply accessing the Child Data through another request.
Any and all suggestions would be greatly appreciated.
I had a similar issue with EF types and Web API recently. Depending on how your generated EF models are setup, the navigation properties may result in circular dependencies. So if your generated Activity class has a Task reference the serializer will try to walk the object graph and get thrown in a little nasty cycle.
One solution would be to create a simple view model to get the serializer working
public class TaskViewModel {
public TaskViewModel ()
{
this.Activities = new List<ActivityViewModel>();
}
public int TaskId { get; set; }
public string TaskSummary { get; set; }
public string TaskDetail { get; set; }
public virtual IList<ActivityViewModel> Activities { get; set; }
}
public class ActivityViewModel{
public ActivityViewModel()
{
}
//Activity stuff goes here
//No reference to Tasks here!!
}
Depending on what you're doing, you may even be able to create a flatter model than this but removing the Task reference will help the serialization. That's probably why it worked when Activities was empty

How do I design a specific super class

I am trying to refactor a solution to bring on board another project.
I have a Core project where common classes across projects reside.
I've tried to simpify my question by using 2 imaginary projects: Holidays and Weather...
I have a file load process setup for the Holidays project which has the following 2 classes:
public class Job
{
public virtual string CreatedBy { get; set; }
public virtual DateTime? CreatedDate { get; set; }
public virtual Security Security { get; set; }
protected IList<File> _files = new List<File>();
public virtual IEnumerable<File> Files
{
get { return _files; }
}
}
public class File
{
public virtual string FileName { get; set; }
public virtual FileType FileType { get; set; }
public virtual FileStatusType FileStatusType { get; set; }
public virtual Job Job { get; set; }
}
The file load process for the Weather project has exactly the same structure as Holidays, except that the Jobs class does not have a Security property.
My question is, is it possible to somehow move both classes into the Core project to allow both projects to use them?
Obviously Weather does not need the Security property, so I was thinking I would have a Core.Job class without Security, and then extend the Core.Job in Holidays.Job.
But once I do that, in the Core.File class, what Job is it referring to? As it sits in the Core project it must be the Core.Job.
So would I then need to have Job and File sit in Holidays, and Weather (and any other future projects) use the Core.Job and Core.File?
I don't want the Core project to have any references to sub projects.
I am using NHibernate, and so have mapping files - adding to the complexity.
Hope this is clear enough
Thanks
You can certainly do this, but I am not sure whether it brings you true benefit:
Does the Core itself work with the base Job in any way? If it does not, implementing Job separately in each project may help you keep coupling loose, even though I'd a little redundant. In code I wrote, I have sometimes introduced unnecessary dependencies by extracting interfaces without adding true benefit. This is why I am a bit precautious.
In case Core does acutal work with it, the part to refactor into the common base Job is perhaps the interface it works with.
You may think of an interface instead of a base class. Security may semantically belong to another interface. Moreover, you hand over a lot of control over your classes to the Core.
Do you ever hand a job from one project to another (or are they mapped to the same DB table via NHibernate?)? If you don't, an internal redundant class may be fine too.
Not very clear why confuse on the soluton offered by you (assuming that I right understood you)
//Core DLL
public class Job
{
public virtual string CreatedBy { get; set; }
public virtual DateTime? CreatedDate { get; set; }
protected IList<File> _files = new List<File>();
public virtual IEnumerable<File> Files
{
get { return _files; }
}
}
in the Hollidays you have
public class HollidayJob : Job
{
public virtual Security Security { get; set; }
}
in Weather simply use a type Job, if it selfsufficient.
In this case you refer CoreDLL from Holliday project and Weather. When you serialize it via NHibernate it for HollidayJob save one field more, but when Weather reads the same table it skips that field, as don't know anything, and don't actually care abotu it.
Hope this helps.

Categories