Unable to access data in an ASP.NET MVC web application using Entity Framework and SQL Server database - sql

In an ASP.NET MVC web application, I have created the following entity:
[Table("tblEmployee")]
public class Employee
{
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
}
But, when I try to retrieve data from a database table called tblEmployee using Entity Framework, I get an error. What I have done until now is:
Created a database MVCDemo with "." as server name and using Windows authentication containing a table called tblEmployee
Installed Entity Framework
Added EmployeeContext.cs class file to Models folder
Code:
namespace MVCDemo.Models
{
public class EmployeeContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
}
}
Added a connection string to web.config file in the root directory
<connectionSrtings>
<add name="EmployeeContext"
connectionString="server=.; database=MVCDemo; integrated security=SSPI"
providerName="System.Data.SqlClient;" />
</connectionSrtings>
Added Details actionResult to EmployeeController to show employee details:
namespace MVCDemo.Controllers
{
public class EmployeeController : Controller
{
// GET: Employee
public ActionResult Details(int id)
{
EmployeeContext employeeContext = new EmployeeContext();
Employee employee = employeeContext.Employees.Single(e => e.EmployeeId == id);
return View(employee);
}
}
}
Finally, I added the following code to Global.asax to prevent initialization:
Database.SetInitializer<MVCDemo.Models.EmployeeContext>(null);
The problem is when I run the application I get this error:
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.
and when I comment connection strings out and try to reach
http://localhost:60613/Employee/Details/1
to show details of 1st employee, I get this error:
System.Data.Entity.Core.EntityException: 'The underlying provider failed on Open.'SqlException: Cannot attach the file 'C:\Users\arya\source\repos\MVCDemo\MVCDemo\App_Data\MVCDemo.Models.EmployeeContext.mdf' as database 'MVCDemo.Models.EmployeeContext'.

Check your tag name, it is incorrect. It will trigger the error definitely.
<connectionSrtings>
It should be:
<connectionStrings>
Update:
Since you have another issue, fix the last part of your connection string:
providerName="System.Data.SqlClient;
Remove the semi-colon at the end of SqlClient.

This is because if you have the database named MVCDemo in the SQL Server then its fine, otherwise code first approach looking for MVCDemo database in SQL Server. If you dont have the database in SQL Server, then try this connection string to create the mdf file first.
connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-MVCDemo-20200820010246.mdf;Initial Catalog=aspnet-MVCDemo-20200820010246;Integrated Security=True"

First of all, I couldn't see your database connection. Yes you have teached the table but you didn't tell the program where to put those infos. Something like:
optionsBuilder.UseSqlServer("Data Source=databaseName")
Second possible reason is your program don't know where to go at the beginning. I had those error before and solved it with using default map.
Third reason, this probably not true but, you wrote "connectionSrtings" wrong. As I say, it's probably not that but I wanted to mention if it is.

Related

MVC DBContext, how to connect to a table?

im just creating my first MVC applicaiton and am having trouble connecting to my database located on my sql server.
i have added the connection string to the web config as normal, created a model with all the fields in.
i created a model and created a new DBContext as there wasnt one listed. this created the below file
im not sure how it connects to the right table in my SQLDB, how do i do this?
also how do i make it run stored procedures?
Thanks
public EquipmentDBContext()
: base("name=ITAPPConnectionString")
{
}
public DbSet<Equipment> Equipments { get; set; }
public EquipmentDBContext()
: base("name=ITAPPConnectionString")//this name should be the name of database
{
}
public DbSet<Equipment> Equipments { get; set; }
here you say you have a
Datamodoel called Equipment. Your context also defines a single property, Equipments, which is of type DbSet. This property acts as a collection that allows you to query the data in you table in database as though it were an in-memory collection of objects.
So, if you create an object of class EquipmentDbContext in controller named lets say db, then you can access the data in table with something like
db.Equipments
To expand further on Cybercop's answer you would do something like this
using (var context = new EquipmentDBContext())
{
var equipments = context.Equipments.ToList();
var equipment = context.Equipments.FirstOrDefault(c=>c.Id == 1);
var blueThings= context.Equipments.Where(c=>c.Color == "blue").ToList();
}

Configuring Fault Contract Exception Handlers in Enterprise Library 6 for WCF

How do you map additional properties of an exception to your custom fault contract when using Enterprise Library 6's Exception Handling Application Block?
This article describes the FaultContractPropertyMapping the same way this one does. If you have a fault contract like so:
[DataContract]
public class SalaryCalculationFault
{
[DataMember]
public Guid FaultID { get; set; }
[DataMember]
public string FaultMessage { get; set; }
}
How do you add another property and map it to the original exception? Lets say I want to show the Stored Procedure name to the client using a new property:
[DataMember]
public string StoredProcedureName { get; set; }
I try editing the mapping shown on page 90 of the "Developer's Guide to Microsoft Enterprise Library-Preview.pdf" which can be found here but it does not seem to work. My new mapping looks like this:
var mappings = new NameValueCollection();
mappings.Add("FaultID", "{Guid}");
mappings.Add("FaultMessage", "{Message}");
mappings.Add("StoredProcedureName", "{Procedure}"); //SqlException has a Procedure property
And here is the policy.
var testPolicy = new List<ExceptionPolicyEntry>
{
{
new ExceptionPolicyEntry(typeof(SqlException),
PostHandlingAction.ThrowNewException,
new IExceptionHandler[]
{
new FaultContractExceptionHandler(typeof(SalaryCalculationFault), mappings)
})
}
};
var policies = new List<ExceptionPolicyDefinition>();
policies.Add(new ExceptionPolicyDefinition(
"TestPolicy", testPolicy));
exManager = new ExceptionManager(policies);
ExceptionPolicy.Reset();
ExceptionPolicy.SetExceptionManager(exManager);
When I do this and catch the FaultException on the client and inspect it, the StoredProcedureName is always empty. Why doesn't it map from the SqlException to the new property in my fault exception?
It turns out you shouldn't actually place the code you expect an exception for inside of the ExceptionManager.Processs() method. I was doing this before:
exManager.Process(() => wimDAL.Execute_NonQueryNoReturn(sc), "TestPolicy");
Insead, just execute the code as normal.
wimDAL.Execute_NonQueryNoReturn(sc);
This does not follow what the "Developer's Guide to Microsoft Enterprise Library-Preview.pdf" says but I guess the documentation is still a work in progress. I hope this helps someone else.

LightSwitch - bulk-loading all requests into one using a domain service

I need to group some data from a SQL Server database and since LightSwitch doesn't support that out-of-the-box I use a Domain Service according to Eric Erhardt's guide.
However my table contains several foreign keys and of course I want the correct related data to be shown in the table (just doing like in the guide will only make the key values show). I solved this by adding a Relationship to my newly created Entity like this:
And my Domain Service class looks like this:
public class AzureDbTestReportData : DomainService
{
private CountryLawDataDataObjectContext context;
public CountryLawDataDataObjectContext Context
{
get
{
if (this.context == null)
{
EntityConnectionStringBuilder builder = new EntityConnectionStringBuilder();
builder.Metadata =
"res://*/CountryLawDataData.csdl|res://*/CountryLawDataData.ssdl|res://*/CountryLawDataData.msl";
builder.Provider = "System.Data.SqlClient";
builder.ProviderConnectionString =
WebConfigurationManager.ConnectionStrings["CountryLawDataData"].ConnectionString;
this.context = new CountryLawDataDataObjectContext(builder.ConnectionString);
}
return this.context;
}
}
/// <summary>
/// Override the Count method in order for paging to work correctly
/// </summary>
protected override int Count<T>(IQueryable<T> query)
{
return query.Count();
}
[Query(IsDefault = true)]
public IQueryable<RuleEntryTest> GetRuleEntryTest()
{
return this.Context.RuleEntries
.Select(g =>
new RuleEntryTest()
{
Id = g.Id,
Country = g.Country,
BaseField = g.BaseField
});
}
}
public class RuleEntryTest
{
[Key]
public int Id { get; set; }
public string Country { get; set; }
public int BaseField { get; set; }
}
}
It works and all that, both the Country name and the Basefield loads with Autocomplete-boxes as it should, but it takes VERY long time. With two columns it takes 5-10 seconds to load one page.. and I have 10 more columns I haven't implemented yet.
The reason it takes so long time is because each related data (each Country and BaseField) requires one request. Loading a page looks like this in Fiddler:
This isn't acceptable at all, it should be a way of combining all those calls into one, just as it does when loading the same table without going through the Domain Service.
So.. that was a lot explaining, my question is: Is there any way I can make all related data load at once or improve the performance by any other way? It should not take 10+ seconds to load a screen.
Thanks for any help or input!s
My RIA Service queries are extremely fast, compared to not using them, even when I'm doing aggregation. It might be the fact that you're using "virtual relationships" (which you can tell by the dotted lines between the tables), that you've created using your RuleEntryTest entity.
Why is your original RuleEntry entity not related to both Country & BaseUnit in LightSwitch BEFORE you start creating your RIA entity?
I haven't used Fiddler to see what's happening, but I'd try creating "real" relationships, instead of "virtual" ones, & see if that helps your RIA entity's performance.

invalid value for key attachdbfilename mvc 4

I'm doing a very basic MVC 4 project. I have a simple model and a dbcontext. I am trying to take input from a form and save it using the dbcontext.
Here's my codes,
In the controller
public ActionResult FormShow(Models.bullseye sampbe)
{
if (ModelState.IsValid)
{
var db = new bullseyeDataContext();
db.bullseyes.Add(sampbe);
db.SaveChanges();
return RedirectToAction("FormShow");
}
return FormShow();
}
In the dbcontext
public class bullseyeDataContext : DbContext
{
public DbSet<bullseye> bullseyes { get; set; }
static bullseyeDataContext()
{
Database.SetInitializer(new DropCreateDatabaseAlways<bullseyeDataContext>());
}
}
And the connectionstring is
<add name="MvcFourFirstTouch.Models.bullseyeDataContext"
connectionString="Data Source=(LocalDb)\v11.0;
Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\MvcFourFirstTouch.Models.bullseyeDataContext.mdf" providerName="System.Data.SqlClient" />
And when i submit the form i'm getting invalid value for key attachdbfilename. Where's the problem??
Updated
The problem is with your connection string. AttachDBFileName does not like the value you've specified to it. Could be an issue with the db name, or an issue with LocalDB, or the lack/presence of an extra \ in the paths.
However, if you have no explicit reason for using AttachDBFileName, then I would suggest replacing AttachDbFileName=[...].mdf with Initial Catalog=yourDBName. You avoid a lot if issues this way :)

Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.DLL in windows phone 7

Created a WCF service and published in IIS. I tried to access this service in windows phone7 so i implement it by installing json.net from Nuget package. Got Serialization of json in correct format.But Deserialization of json fails in webClient_OpenReadCompleted method. I given my code template here
private void webClient_OpenReadCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string s = e.Result.ToString();
Customer deserCustomers = JsonConvert.DeserializeObject<Customer>(s);
int id=deserCustomers.CustomerId;
string n = deserCustomers.CustomerName;
lstCustomer.ItemsSource = deserCustomers.ToString();
}
While reaching the below code got exception as follows:
Customer deserializedCustomers = JsonConvert.DeserializeObject(s);
An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.DLL but was not handled in user code.
Give me suggestions to solve this error
Actually is quite simple , you should just make your class interface of a list, because your json is array something like:
public class Customer:List<object>
{
public int CustomerId{get; set;}
public string CustomerName{get; set;}
}
than everything is pretty basic
var deserCustomers = JsonConvert.DeserializeObject<Customer>(s);
foreach (var cust in deserCustomers)
{
....
}
hope it's work (: