How to retrieve data from SQL Server database into the application [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 months ago.
Improve this question
I am creating a web app using Razor pages in ASP.NET Core. How can I retrieve data from my database? I am trying to connect my database with the application.
[Table("Employee")]
public class Employee
{
[Key]
public Guid EmployeeId { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
[Required]
[StringLength(100)]
public string Address { get; set; }
public byte Status { get; set; }
}
This is how the models look which is auto-created after running the command scaffold-DbContext.
How can I retrieve data from the DB?

You only create your model. You had already created the database, please skip step 6.
To retrieve data from an existing database in EF Core, you should do the following step:
1. Create an App
Create an ASP.NET Core app .NET 6.
Install the following NuGet packages:
Microsoft.EntityFrameworkCore.SqlServer 6
Microsoft.EntityFrameworkCore.Tools 6
2. Create the Models
Create a model for your existing SQL Server database. You can create the model by Scaffold-DbContext command or manually.
To create models from existing SQL Server database use Scaffold-DbContext command:
Scaffold-DbContext "Server=(localdb)\\mssqllocaldb;Database=WebAPI;Trusted_Connection=True;MultipleActiveResultSets=true" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
In Visual Studio, the commands is typed in Package Manager Console.
The model could be created manually as follow:
public class Employee
{
[Key]
public Guid EmployeeId { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
[Required]
[StringLength(100)]
public string Address { get; set; }
public byte Status { get; set; }
}
You have done this step.
3. Create a Context
If you used Scaffold-DbContext command, the dbContext was created automatically. The name of the db context class is [Your Database Name]Context. In this example is WebAPIContext.
You could also create db context class manually as follow:
public class WebAPIContext: DbContext
{
public DbSet<Employee> Employees { get; set; }
}
4. Configure database connection
Add the following code to appsettings.json file
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=WebAPI;Trusted_Connection=True;MultipleActiveResultSets=true"
},
5. Add AddDbContext service
Add the following code to Program.cs file
builder.Services.AddDbContext(options =>
options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"))
, optionsLifetime: ServiceLifetime.Scoped);
6. Add-Migration and Update-Database command
Use the Add-Migration init1 command to scaffold a migration to apply these changes to the database.
Run the Update-Database command to apply the new migration to the database.
Remark: If you have not created the database, you should do step 6.
Now you can retrieve data from SQL database and make CRUD operations on your database.
To list employees, replace the following code in the Razor page:
public class IndexModel : PageModel
{
private readonly WebAPIContext _context;
public IndexModel(WebAPIContext context)
{
_context = context;
}
public List<Employee> Employees { get; set; }
public async Task OnGetAsync()
{
Employees = _context.Employees.ToList();
}
}

You have great tutorial in answer above, first of all check key aspects:
have you made connection to Db? (DB Context)
is Db connection string correct (in appsettings.json)
have you registered DbContext in services in Startup.cs to use in Dependency Injection
are you properly using db context in other classes - you can compare with tutorial approach to db context
cheers

Related

How to generate database from classes using EF Code First [.Net 5.0]

I'm working on C# winForms project (.NET 5.0) , Iam a newbie in EntityFramework code first, I worked with EF DB First many times but I decide to go through EF Code First.
My Class
class Student
{
public int ID { get; set; }
public string Name { get; set; }
}
My Db Context class I created
class XMDBContext:DbContext
{
public XMDBContext() : base()
{
}
public DbSet<Student> Students { get; set; }
}
Now I want to know how can I use Visual Studio or Entity Framework to generate the database(preferred if in SQL Server) from these classes ?
There are different ways to create the database in a code first scenario. But the easiest approach would be to just run your application and read or write to the DbContext. It will then automatically create the database "on access".
The official microsoft example is also very helpful if you are doing this the first time: Code First to a New Database

Adding New Table Entity Framwork Code First Approach

That solution does not work in .net core 2 tied to SQL Server 2016. Original Question: Trying to jump into entity framework, using the "Code First Approach". I have my new class setup “NewTable” shown below. I can’t figure out what in the Program Manger Console I need to type to get this table created in my Default Connection String (pointing to a local instance of Sql Server 2016). The database is working and the user in this .net core 2 web app can register his/her name then log in using that new created account. Thanks in advance!!
Default Connection String:
"ConnectionStrings": {
"DefaultConnection" "Server=localhost\RCDSE_Dev;Database=Some Database;User ID=sa;Password=SomePass;"
},
[Table("NewTable")]
public class NewTable
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)] //Database generated key
[Key] //Primary Key
public long Id { get; set; }
[Required]
public string Manager { get; set; }
}
public class NewTableContext : DbContext
{
public DbSet<NewTable> NewTables{ get; set; }
}
Add a constructor to the DbContext as below:
public class NewTableContext : DbContext
{
public DbSet<NewTable> NewTables{ get; set; }
public NewTableContext() : base("DefaultConnection") { }
}
I figured this out. Will post a detailed step by step guide for others in the next couple of days. There are specific things that need to be done in .net core 2 project file that were NOT COVERED in any of the referenced examples by users here. Thanks for all the help..it got me somewhat pointed in a direction, to find the right direction...lol.

ASP NET MVC 3 - How to reset database in code first, with two tables and Database.Setinitializer?

My problem lies in the lack of experience in MVC. Basically, I have two tables in DB
-Person
-Offer
For each I have created a model and a controller and a model, so the structure looks like that:
public class Offer
{
public int OfferID { get; set; }
public string OfferTitle { get; set; }
public string State { get; set; }
public string Description { get; set; }
}
public class OfferDBContext : DbContext
{
public DbSet<Offer> Offers { get; set; }
}
This is the Offer model.
public class Person
{
public int PersonID { get; set; }
public string Username { get; set; }
public DateTime Birthday { get; set; }
public string Education { get; set; }
public string Email { get; set; }
}
public class PersonDBContext : DbContext
{
public DbSet<Person> Persons { get; set; }
}
This is the Person model.
Firstly I created the Person model, that added itself to db without any problems. Then I wanted to add Offer table, and I had to use the DropCreateDatabaseIfModelChanges method. I used it for OfferInitializer and PersonInitializer and then there is the Global.asax.cs file
protected void Application_Start()
{
Database.SetInitializer<OfferDBContext>(new OfferInitializer());
Database.SetInitializer<PersonDBContext>(new PersonInitializer());
//Database.SetInitializer<PersonDBContext>(new PersonInitializer());
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
From what I understand, I cant do that simply because I am dropping database 2 times, each time populating only one table at a time. How do I reorganize it all, so that I can populate both or more tables at a time, or the whole database?
First things first, you should not create individual DbContext classes for each table. You should instead put all your DbSets in the same DbContext. Doing this will simplify things greatly for you.
Secondly, you should look into using migrations. You should start using them very early in your project.
You work with code first migrations using the Package Management Console.
enable-migrations
Does exactly what the name implies. Initializes migrations in your project. This will create a folder inside your project and generate the files needed.
add-migration InitialCreate
This creates a migration. InitialCreate is actually a string and you can change it to whatever you want. This command will generate the scripts needed to create the database from strach.
update-database
This command verifies the database and applies the migration (or migrations - there can be multiple) required in order to get the database up-to-date.
This is the initial setup. If you do further changes to your first code first classes, or add more, you will just have to add a new migration and then execute it.
add-migration AddedFirstName
update-database
It's that simple!
There are some more advanced concepts like seed, rollback, update to specific migration, etc., but what I have typed above covers the basics and the day to day usage of migrations.
I recommend you to read this article which explains everything in much more detail: http://www.asp.net/mvc/overview/getting-started/getting-started-with-ef-using-mvc/migrations-and-deployment-with-the-entity-framework-in-an-asp-net-mvc-application

Error While Enabling Code-First Migrations On Mobile Services Database

I have an Azure Mobile Services project (C# backend) that I recently created and attached to an Azure SQL database. I have been trying to enable Code-First Migrations on that backing database, but it throws errors when I try to update the database.
I ran through all of the conventional steps to enable migrations (Enable-Migrations, Add-Migration). But when I try to Update-Database, it returns the following error:
Cannot create more than one clustered index on table 'dbo.Appointments'. Drop the existing clustered index 'PK_dbo.Appointments' before creating another.
Why is this happening? There aren't any tables in my database, and the project is pretty much the default.
Several of the answers about deriving from a custom entity class will work, but they are not the ideal solution. As the EF team (and others) have mentioned, you need to simply add this line to your Context Configuration constructor.
SetSqlGenerator("System.Data.SqlClient", new EntityTableSqlGenerator());
This will remove your errors when creating migrations and allow you to update the database via powershell command.
If you are getting this error on update-database after creating the migration class, Then have a look # your migration class. The migration class will take primary is clustered index. So remove that from the up() method.
.PrimaryKey(t => t.Id, clustered: false)
.Index(t => t.CreatedAt, clustered: true);
If you using it on azure mobile service, do not call 'update-database' manually.
refer http://azure.microsoft.com/en-in/documentation/articles/mobile-services-dotnet-backend-how-to-use-code-first-migrations/
I was fighting with this problem today for a few hours. Until I found this link:
How to make data model changes to a .NET backend mobile service
If you follow the instructions there, it will definitely work. The main thing is, that the migration will take place, when you hit F5 during a local debugging session.
I just had the same issue.
It is caused by the definition of EntityData that is our base class:
public class OrgTest : EntityData
{
public string Prop1 { get; set; }
}
I replaced EntityData with my own implementation "CustomEntity" where I removed the attribute [Index(IsClustered = true)] on the CreatedAt column:
public abstract class CustomEntity : ITableData
{
// protected CustomEntity();
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[TableColumn(TableColumnType.CreatedAt)]
public DateTimeOffset? CreatedAt { get; set; }
[TableColumn(TableColumnType.Deleted)]
public bool Deleted { get; set; }
[Key]
[TableColumn(TableColumnType.Id)]
public string Id { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
[TableColumn(TableColumnType.UpdatedAt)]
public DateTimeOffset? UpdatedAt { get; set; }
[TableColumn(TableColumnType.Version)]
[Timestamp]
public byte[] Version { get; set; }
}
and now I inherit from this one:
public class OrgTest : CustomEntity // EntityData
{
public string Prop1 { get; set; }
}
Probably I will have troubles further on, but for the time being I can create my model!
Hope you can also start like this!
See this article:
avoid nightmares using ef first migration in azure mobile services
EntityData define a cluster indext to CreateAt and Id is by default a cluster index, this way it provide an error and you should define only one.

C# .Net class library database schema create

Im creating a class library that will be used in several projects. This library includes a handfull of entities with associated tables in the database. My question is: how do I create these tables when I include this library in a project?
I suspect you want a library of objects that are used to generate a database?
If so you can achieve this with EntityFramework CodeFirst.
At minimum you'll need your objects and a DbContext.
a typical set up maybe as follows:
Entities
public class Person {
public string FirstName { get; set; }
public string LastName { get; set; }
}
DbContext
public class MyDbContext : System.Data.Entity.DbContext {
public MyDbContext(string nameOrConnectionString) : base(nameOrConnectionString)
public DbSet<Person> People { get; set; }
}
These would live in your project and when you add a reference to it, for example a web project. There are different ways to build the Database, you could call the constructor (MyDbContext) from your web project and pass a connection string to a server.

Categories

Resources