ASP.NET: Errors in autogenerated .Designer.cs file for Model - asp.net

I'm new to ASP.NET and having a problem with a tutorial.
I've created a new MVC4 Project in VS2012 Express for Web.
And I've added a SQL Database with 1 Table "Persons" and filled it with some random testdata:
Id int (primary key, is identity=true)
name varchar(50)
birthdate date
adam 01.01.2001
berta 02.02.2002
As a Model I've used ADO.NET Entity Data Model, named it "PersonsModel.edmx"
and used the Personsdatabase for it.
To see the PersonsModel.Designer.cs file, I activated "Codegeneration Status" to "Standard". Refreshed and clicked on the PersonsModel.Designer.cs file.
But in this file I've errors... So I wanted to use something like this in my controller:
HomeController.cs:
PersonsEntities1 db = new PersonsEntities();
db.person...
but it doesn't work, and I think(?) it's because of the errors in the .Designer.cs file.
PersonsModel.Designer.cs: e.g.:
public PersonsEntities1() : base("name=PersonsEntities1", "PersonsEntities1")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
errors in the base: ... line
and in ContextOptions.
Unfortunately I've no english VS, but it says something like:
The best accordance für the overloaded System.Data.Entity.DbContext(string, System.Data.Entity.Infrastructure.DbCompiledModel)-Method has some invalid arguments
And no definition found for "ContextOptions", there is no method "ContextOptions" which accepts "MvcApplication7.Models.PersonsEntities1" as a first argument.
I'm a bit confused, because I did it like in the tutorial explained.

I think this code is in error:
base("name=PersonsEntities1", "PersonsEntities1")
There is no constructor that takes two strings. Your second argument is supposed to be of type DbCompiledModel. (See here.)
Now, I don't know why your designer would produce code that can't compile, so I'm wondering whether you have the wrong version of Entity Framework installed.

Apparently the problem was VS2012. It all works with VS2010.
I've downloaded the installer again from asp.net/mvc and added Visual Web Developer 2010 Express. After installation of VS2010 and all dependencies I tried the tutorial again and all works fine now. No wrong code in the .Designer.cs file :).
Thanks a lot Ann L. for your support. Your hint (wrong version of Entity Framework installed) prompt me to try another VS version.
In addition I've to say: I also tried VS2012 Ultimate (complete DVD version) but it didn't help.

Related

Navigations can only target entity types with keys

I am working on a project with a 'database first' approach rest API backend. I am using ASP .Net Core 3.1 and Entity Framework 3.1.1.
I ran a script to scaffold the database into the models and db context class. However, some of the model building functions have tables/models without keys x.hasnokey(). I thought this would be fine but I get an error trying to hit the endpoint that states
ERROR : InvalidOperationException:
The navigation '' cannot be added because it targets the keyless entity type 'AAA'
Navigations can only target entity types with keys
This happens in a few different locations and this originally ran okay in the past. This is running on SQL Server 2012 (version 11). I am not sure how I can solve this issue, I have limited entity/sql experience and I just don't know where to begin. Here is the offending lines (inside DB Context):
modelBuilder.Entity<AAA>(entity =>
{
entity.HasNoKey();
entity.ToTable("BBB_AAA");
entity.HasOne(d => d.BBB)
.WithMany(p => p.AAA)
.HasForeignKey(d => d.CCC)
.OnDelete(DeleteBehavior.ClientSetNull)
...
}
The script I used to scaffold the models and db context was (generic version):
PM> Scaffold-DbContext "Server=.\SQLExpress;Database=SchoolDB;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
I believe this might be that the database that was originally created about 10-15 years ago, cannot be made into an ORM so easily as I would have hoped. It could also a versioning issue, the scaffolding script I ran is incorrect, or if I just am out of my depth but I would appreciate being pointed in the right direction. Thank you!
This error usually comes because of Primary Key issue.
In my Case I was running this query and result was same problem you mentioned
var exists = await _dbDontext.Students.FindAsync(Id);
My Student table has relations with other tables and one of other tables was missing Primary Key.
So two Possible Solutions .
Solution 1 :
Make Primary Key column in your table that is mentioned in your error.
Solution 2 :
If things are complicated , just delete the table and Re Create It. It would work fine
I think you have two options,
1- Go and add key to the table.
2- check the following link
https://learn.microsoft.com/en-us/ef/core/modeling/keyless-entity-types
Thanks

Using SQL Server 2012 Geography Data Type with ASP.Net - DataReader.GetFieldType(x) returned null

I've written an ASP.Net 4 Application which has been working perfectly. However, I decided to make use of the new Geography Data Type in Sql Sever 2012. This worked perfectly on my local machine but fails when I upload.
I get there error "DataReader.GetFieldType(9) returned null." when doing a usual "select * FROM Table" query on a table that contains one of these datatypes.
I have searched the various threads regarding adding a reference to the Microsoft.SqlServer.Types.dll into my project and changing Copy Local to true. However I am getting the same error.
I run the database and the web server on two separate servers so I don't think there are any assemblies on the web server unless I upload them with my project.
Am I missing any other assemblies that are needed? or any other settings?
I've taken days trying to solve this and uploading variouse libraries. Any help would be appreciated.
msdn
When the compatibility level is 100 or below in SQL Server 2012 then the geography data type has the following restrictions:
•Each geography instance must fit inside a single hemisphere. No spatial objects larger than a hemisphere can be stored.
•Any geography instance from an Open Geospatial Consortium (OGC) Well-Known Text (WKT) or Well-Known Binary (WKB) representation that produces an object larger than a hemisphere throws an ArgumentException.
•The geography data type methods that require the input of two geography instances, such as STIntersection(), STUnion(), STDifference(), and STSymDifference(), will return null if the results from the methods do not fit inside a single hemisphere. STBuffer() will also return null if the output exceeds a single hemisphere.
From what I can tell you will at least need SQL Server installed locally when you initially add the reference. If you can I would try and install SQL Express locally first (you do not need to use it just install it) and then try your code again to see if that is the problem.
References:
DataReader.GetFieldType returned null
http://blogs.bing.com/maps/2013/08/05/advance-spatial-queries-using-entity-framework-5/
Edit:
I am more familiar with using spatial types via the entity framework. It seems if you want to use them directly you need to use a nuget package in order to get the required DLLs into the project. From the Microsoft ADO.NET blog page
SqlServerSpatial110.dll – This is a native assembly so it cannot be added as a project reference.
References:
Microsoft ADO.NET Blog
http://blogs.msdn.com/b/adonet/archive/2013/12/09/microsoft-sqlserver-types-nuget-package-spatial-on-azure.aspx
Relevant SO Questions
'Microsoft.SqlServer.Types' version 10 or higher could not be found on Azure
https://gis.stackexchange.com/questions/382/how-can-i-use-sql-servers-spatial-types-from-a-net-application
Spent heaps of time on this, adding references as well, but I found a workaround i want to share.
Should work fine on asp.net as well.
I use the following query to parse me the string representation of the object:
DECLARE #result geography;
SELECT #result = area FROM news WHERE id LIKE #id ;
SELECT ..., #result.STAsText() as area FROM news WHERE id LIKE #id;
And in the asmx (c#) webservice i retrieved my SQLGeography with a parser method:
row["area"].ToString()
After that you can use a parser method to retrieve the SQLGeography object.
/// <summary>
/// Converts a String into an sql geography object.</summary>
/// <param name="pText">The string representation of the sql geography object. </param>
public static SqlGeography GetGeographyFromText(String pText)
{
SqlString ss = new SqlString(pText);
SqlChars sc = new SqlChars(ss);
try
{
if (pText.Contains("POINT"))
{
return SqlGeography.STPointFromText(sc, 4326);
}
return SqlGeography.STPolyFromText(sc, 4326);
}
catch (Exception ex)
{
return SqlGeography.STMPolyFromText(sc, 4326);
throw ex;
}
}
Hope it helps anyone!
In the end I couldn't get it to work as it does on my development machine and I don't want to install Visual Studio or SQL Server Express on the web server so instead I just removed all the queries where I did "SELECT * FROM Table" and the error went away. It still let me do my calculations using the geography field, but doesn't like you trying to show it on the screen. Thanks for all your help!

Entity framework update model from database not generating cs class for newly added table in tt class

I am using entity framework 5 with visual studio 2012.
I do have an existing model. Now I want to add a new table to that existing model. For that I have opened the edxm file and using right click I updated the model successfully.
Now, in "Model Browser" under "EntityTypes" for model, I can see the table name exists. But in Solution Explorer it is not showing the auto-generated .cs file for the table I have added newly under .tt file.
I tried "run custom tool" but it has not generated the class. Also have restarted the Visual Studio but result is the same.
Can anyone help me?
Thanks
Problems
In case you have table name tblEmployee in Database But after the adding 'Entity Data Model' you have Changed Entity tblEmployee to Employee in EDMX file then Save and Build. But Classes for Changed Name are not Generated Automatically in Model1.tt file.
When "Update Model From Database" for adding new table same Problem occurs.
Also not available in MVC When creating view with Model Class/Create Controller With Actions using EntityFramework
This problem is for early version of VS2012.This problem is solved in upgraded version of VS2012.
Solution
we have solution for this with early version of VS2012 & EF 5.0
Follow steps
Right click On Model1.tt and select 'Run Custom Tool' save and Build Now see classes are generated.
Right click On Model1.Context.tt and select 'Run Custom Tool' save and Build Now see property IN Context class is generated like
public DbSet<Employee> Employees { get; set; }
Save and Build Solution
Model1Context context=new Model1Context();
List<Employee> empList= context.Employees.ToList();
This worked for me.
But Keep in mind that still EF 6.0 not able to make Scaffolding when 'creating controller and view using entityframework' in MVC with this viersion of VS2012.
You must Use EF 5.0 or update VS2012 with new update.
Resolved it myself.
The problem was in files filename.Context.tt and filename.tt.
The diagram file name for variable const string inputFile specified in both of the files were different than the existing diagram file (.edmx file). Updated it with existing diagram file name and then updated model from database. Working fine now.
In this case what i do is i just delete the exciting model and then click on add and just add your newly added table for there!
If this is the bug with the edmx file located in a folder it is now fixed - download and install VS 2012 Update 1. You can get it from:
http://www.microsoft.com/visualstudio/eng/downloads#d-visual-studio-2012-update
I have added primary key to the new table. That resolves problem.

Websphere & Tivoli: NPE while trying to create PDAuthorizationContext

I am getting the following error when I try to start my Application...
[java.lang.IllegalStateException: java.lang.NullPointerException^M
at com.tivoli.pd.jutil.kb$1.run(kb$1.java:41)^M
at java.security.AccessController.doPrivileged(AccessController.java:229
)^M
at com.tivoli.pd.jutil.kb.c(kb.java:141)^M
at com.tivoli.pd.jutil.kb.(kb.java:56)^M
at com.tivoli.pd.jutil.PDContext.(PDContext.java:76)^M
at com.tivoli.pd.jazn.PDAuthorizationContext.(PDAuthorizationConte
xt.java:66)^M
I double checked the config file was accessible and I could read it. The code I am using looks as follows...
aC = new PDAuthorizationContext(cFile);
Is there a way to get more information on what is causing the NPE?
More information!!!
After debuging a bit, it appears the issue comes from this code (they use progaurd so it is a little hard to be 100% confident)...
Certificate[] arrayOfCertificate1 = ((KeyStore)???).getCertificateChain("DefaultID");
//Throws Null pointer (presumably because array is null)
Certificate localCertificate1 = arrayOfCertificate1[0];
EVEN MORE INFO
This appears to be some kind of dependency conflict (guess), because if I just create a sample App using PDAuthorizationContext it works fine.
Problem was related to the PD.jar version that I was using. Although I thought I was using one version I was using another. This was because on version was registered in my WebSphere library (under build path in eclipse). Once the proper library was introduced everything worked.

Specflow error using TestDriven.Net - Couldn't Find Type

I'm trying out Specflow for the first time, and have created a VS2010 project with a reference to TechTalk.SpecFlow, as well as nunit.framework. I've added a sample Feature file:
Feature: Addition
In order to avoid silly mistakes
As a math idiot
I want to be told the sum of two numbers
#mytag
Scenario: Add two numbers
Given I have entered 50 into the calculator
And I have entered 70 into the calculator
When I press add
Then the result should be 120 on the screen
When I execuyte the test (using TestDriven.Net), I get the following error:
Test 'T:SpecFlowFeature1' failed: Couldn't find type with name 'SpecFlowFeature1'
System.Exception: Couldn't find type with name 'SpecFlowFeature1'
at MutantDesign.Xml.Documentation.MemberInfoUtilities.FindMemberInfo(Assembly assembly, String cref)
at TestDriven.TestRunner.AdaptorTestRunner.Run(ITestListener testListener, ITraceListener traceListener, String assemblyPath, String testPath)
at TestDriven.TestRunner.ThreadTestRunner.Runner.Run()
Anyone know what I'm missing?
Actually traced this down to how I was running the test. Right clicking the ".feature" file (or anywhere within that file) and selecting "Run Tests" resulted in the error. Right clicking the underlying ".feature.cs" file and selecting "Run Tests" executed correctly. Looks like TestDriven.Net wasn't able to "understand" the "*.feature" file.
I typically start "Couldn't find type..." errors in my references folder and make sure that the library that I'm referencing is being referenced correctly and that the version that's being referenced isn't outdated.
Also, make sure that your SpecFlowFeature1 class isn't mistakenly declared as private. Visual Studio creates new classes (by default) as private and if you don't specify a class as public, it will remain private and not "visible" to outside projects.

Resources