How can I execute a SQL function in MVC?
I am trying to link the results of a table returning function to a class I defined. I have set up the connection string and created the database context with public DbSet<Classname> variable{get; set;} how can i link this to the results of a function
Are you using Entity Framework? Here is an article you can read:
http://rationalgeek.com/blog/function-imports/
Related
I have just created an ASP.NET MVC 4 & WebAPI project. After that I have added .edmx data source to project.
I have multiple databases with the same schema. Dynamically I want to replace connection string using default constructor provided in EF.
But in Model1.Designer.cs, every time I get error like "Member with same signature already declared".
I'm unable to solve this problem.
Yes, it works! All you need to change is the connection string.
And I have just tested it in order to satisfy my own curiosity.
Here are the steps that I took:
Take an existing database and create a model for it.
Create a new empty database.
In SQL Management Studio right click the first database -> Tasks -> Export Data. Export all it's data to the newly created database.
Remove some records from the second database.
Write this code:
TMS_MiscEntities db = new TMS_MiscEntities();
TMS_MiscEntities dbCopy = new TMS_MiscEntities();
dbCopy.Database.Connection.ConnectionString = db.Database.Connection.ConnectionString.Replace("initial catalog=TMS_Misc", "initial catalog=TMS_Misc_new");
Response.Write(string.Format("DB 1 records: {0}<br/>", db.ZipCodes.Count()));
Response.Write(string.Format("DB 2 records: {0}<br/>", dbCopy.ZipCodes.Count()));
Check results:
DB 1 records: 869164
DB 2 records: 868709
Conclude that it works :)
This is how my connection string looks:
<add name="TMS_MiscEntities" connectionString="metadata=res://*/DbModel.csdl|res://*/DbModel.ssdl|res://*/DbModel.msl;provider=System.Data.SqlClient;provider connection string="data source=ws2008;initial catalog=TMS_Misc;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
I'm using Entity Framework 6.1.3. I have added a constructor to my DbContext that takes a string parameter. This string can be the name of the connection stored in your App.config or a full connection string. Something like this:
public partial class MyDBContext : DbContext
{
public MyDBContext(string connectionString)
: base(connectionString)
{
}
// DbSets, OnModelCreating, etc
}
In my case, I manage a multi-tenant application and I use a ContextFactory to build the proper connection string and return my initialized context.
public class ContextFactory
{
public MyDbContext GetContext()
{
string connectionString;
// do some stuff here
return new MyDbContext(connectionString);
}
}
I am new to ASP.Net MVC . Any help is greatly appreciated in resolving my problem.
I am using a LINQToSQL db in my MVC application. For one of the auto generated partial class (Example MyClass assume for table MyClass) , I created another Partial class as MyClass and added DataAnnotations Like following...
namespcae NP
{
[MetadaType(typeof(myData))]
[Serializable()]
public partial class MyClass
{
}
public myData
{
[Required]
public string ID { get ; set ;}
// Other properties are listed here
}
}
In my controller class example MyHomeController
I have a code as follows:
List<MyClass> list = new List<MyClass>();
list = dbContext.StoredProcedure(null).ToList<MyClass>()
session["data"] = list.
above code works fine if I use inProc session state. But if I use SQLServer mode then I get error as
"Unable to serialize the session state. In 'StateServer' and
'SQLServer' mode, ASP.NET will serialize the session state objects,
and as a result non-serializable objects or MarshalByRef objects are
not permitted. The same restriction applies if similar serialization
is done by the custom session state store in 'Custom' mode. "
Can anyone tell me what I am doing wrong here..?. I can see the data is getting populated in ASPState database tables. By application throws error as follows.
Just mark as Serializable all classes whose instances you want to store in Session.
Finally I was able to resolve the issue.
Solution:
Add the below statement before querying the database. In my case I was calling LinqToSQl context( dbContext).
dbContext.ObjectTrackingEnabled = false;
Sample Code:
List empList = new List();
dbContext.ObjectTrackingEnabled = false;
empList = dbContext.SomeStoredProcedure().ToList()
Session["employee"] = empList.
I am using Entity Framework on a project, but am finding the large queries, especially those which use LEFT joins, to be very tedious to write, and hard to debug.
Is it common, or accepted practice, to make use of Views in the database, and then use those views within the EntityFramework? Or is this a bad practice?
the question is not very clear but there is no absolute right or wrong in Software. it all depends on your case.
there is native support for views in ef core but there is no native support for views in EF < 6. at least not in the current latest version 6.3. there is, however, a work around to this. in database first you would create your view via sql normally and when you reverse engineer your database, EF will treat your view as a normal model and will allow you to consume it regularly as you would do in a normal table scenario. in Code First it's a bit more tedious. you would create a POCO object that maps to the columns in your view. notice that you need to include an Id in this POCO class. for example
public class ViewPOCO
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid Id {get;set;}
public string ViewColumn1 {get;set;}
... etc.
}
you would add this POCO class in your DbContext
public class MyDbContext : DbContext
{
public virtual DbSet<ViewPOCO> MyView {get;set;}
}
now you will normally apply the command of adding migration through the package manager console
Add-Migration <MigrationName> <ConnectionString and provider Name>
now in the migration up and down you will notice that EF treats your Model as table. you would clear all of this and write your own sql to add/alter the view in the up and drop the view in the down method using the Sql function.
public override void Up()
{
Sql("CREATE OR ALTER VIEW <ViewName> AS SELECT NEWID() AS Id, ...");
}
public override void Down()
{
Sql("DROP VIEW <ViewName>");
}
First create your view.
Update Your .edmx File.
then use like this.
using (ManishTempEntities obj = new ManishTempEntities())
{
var a = obj.View_1.ToList();
}
I am new to Visual Studio MVC3 and trying to connect to a database. I have my connection string in the web.config file:
add name="con" connectionString="Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;Initial Catalog=myDataBase;
User ID=myUsername;Password=myPassword;" providerName="System.Data.SqlClient"
However, the server has multiple tables. How/where will I specify which table to use when querying the database?
EDIT:
For example, I am looking at this example. How does the application differentiate between the tables to display data? When you call return View(db.Students.ToList()) as in the example in the link, how does the application know to look in the student table and not in the enrollment table?
How does the application differentiate between the tables to display
data? When you call return View(db.Students.ToList()) as in the
example in the link, how does the application know to look in the
student table and not in the enrollment table?
The db.Students part comes from Entity Framework.
Read the "Creating the Database Context" section in the link that you posted.
You will find the following code there:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using ContosoUniversity.Models;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace ContosoUniversity.Models
{
public class SchoolContext : DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Course> Courses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
}
This sets up the database context, which is basically Entity Framework's "setup", from where it knows which C# class it has to map to database tables.
So db.Students (from your question) is actually a DbSet<Student>.
Entity Framework's default convention looks like this: it tries to map a class to a table with the same name.
Usually, it would map the Student class to a table named Students (pluralized), but you can change/override these conventions...which they also did in this example, in this line:
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
This is also explained in the tutorial, directly under the above code.
Quote from the tutorial:
This code creates a DbSet property for each entity set. In Entity
Framework terminology, an entity set typically corresponds to a
database table, and an entity corresponds to a row in the table.
The statement in the OnModelCreating method prevents table names from
being pluralized. If you didn't do this, the generated tables would be
named Students, Courses, and Enrollments. Instead, the table names
will be Student, Course, and Enrollment. Developers disagree about
whether table names should be pluralized or not. This tutorial uses
the singular form, but the important point is that you can select
whichever form you prefer by including or omitting this line of code.
I've got an application set up with RIA Services, Entity Framework 4, and Silverlight 4. It is set up in the standard fashion prescribed on MSDN here: Walkthrough: Creating a RIA Services Solution
I've written a new method (or property) against one of the entity objects which resides on the server; I would like this method (or property) to also be generated (automagically) on the client. i.e.
I have a table in my database called Customer which has two fields: FirstName and LastName
(ASP.NET project - server side) EF has created a corresponding partial class called Protocol that has two properties: FirstName and LastName
(ASP.NET project - server side) In another file, I'm using the partial class mechanism to define a method (or property) to return the FirstName and LastName together in a string, e.g.
public function ReturnFullName() as String ...
public property FullName() as String ...
Is there a way for ReturnFullName() and FullName() to be generated in on the client side (my Silverlight application)? Or do I have to implement the method / property on the client side as well?
Create a .shared.cs or .shared.vb file with a partial class of the entity in it.
For example:
Partial Public Class Persoon
Public Function GetFullName() As String
Return Me.Voornaam & " " & Me.Naam
End Function
End Class
public partial class Persoon
{
public string GetFullName()
{
return this.Voornaam + " " + this.Naam;
}
}
It will then generate on client side to.
Methods in your Domain objects on the server side are not generated on the client side. (One reason for that is that obviously you could use .NET Framework features in these methods that are not available in Silverlight.) Properties are just copied with their signature, using class variables.
A solution to that problem is having a partial .cs file for your Customer class where you define these methods and create a link to that file in your Silverlight project. Of course, you can only use libraries in the using statements that are also available in Silverlight.