C# .Net class library database schema create - c#

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.

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

two databases in one system in asp.net core

I have a system that I work on which already have a database using code first. I had asked to connect my system to other database to get some data from one table in it which is employees table how can I do that.
the two DBs on the same server
After I searched in google i find noting clear.
With Entity Framework you able to connect and use data from multiple sources.
I suggest you to create a new context. The context is a class that inherit from DbContext.
You have to provide a new connection string for your "Employee" context.
//Entity class representation
public class Employee
{
public int Id { get; set; }
}
//Entity Framework context
public class SecondContext : DbContext
{
public SecondContext(DbContextOptions<SecondContext> options) : base (options)
{
}
public DbSet<Employee> Employees { get; set; }
}
At the end, you will have two contexts in your application.

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

Entity Framework Shared Core Functionality Library

I am programming a few projects which have some core functionality which are similar and then their own functionality outside of that.
I was considering making a class library, using Entity Framework with Code First in order to provide some shared functionality and the database tables that go with it.
For example, I may want to use the class library to send an email and then use entity framework to log in a database table that an email is sent.
This class library would be added into another project, which also uses entity framework - in the same database. So now I would like the database to "build itself", creating the email logging table and some other functionality, e.g. products of some sort.
I have not used Entity Framework before, will having two dlls end up causing any kind of confusion because they're both pointing to the same database but expect different tables? e.g. would they be inclined to delete tables because they don't appear in the code?
Will it also cause problems if I end up over-lapping, e.g. if I want to do a join on all products (Project Entity Framework) which have had an email (Class Library Entity Framework) sent out, would I be able to do a join via linq?
You'll want to keep everything in one DbContext. You can do this by using interfaces to group the entities in each dll, then declare a concrete DbContext class that combines them all in your top-level code.
Project1:
public interface IMyProj1DbContext : IDbContext
{
DbSet<Person> People { get; set; }
DbSet<Place> Places { get; set; }
}
Project2:
public interface IMyProj2DbContext : IDbContext
{
DbSet<Customer> Customers { get; set; }
DbSet<Order> Orders { get; set; }
}
And you'll need a third project that defines the common members:
public interface IDbContext
{
int SaveChanges();
}
Now in the code where all these come together, you can declare a single DbContext class that inmplements all of the interfaces:
public class MyDbContext : DbContext, IMyProj1DbContext, IMyProj2DbContext
{
public DbSet<Person> People { get; set; }
public DbSet<Place> Places { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<Order> Orders { get; set; }
}
Now, you will want to write the code that uses the two different contexts and that code will live inside the individual dlls for each context. But how can you do that?
public class PersonFinder
{
public Person FindPersonByLocation(Place placeToSearch)
{
using (var db = new ???)
{
return db.People.SingleOrDefault(p => p.Location_Id == placeToSearch.Id);
}
}
}
You can't reference the concrete DbContext here because that will cause a circular dependency. The key is to inject the DbContext object at run-time:
public class PersonFinder : Disposable
{
IMyProj1DbContext _db;
public PersonFinder(IMyProj1DbContext db)
{
_db = db;
}
public Person FindPersonByLocation(Place placeToSearch)
{
return _db.People.SingleOrDefault(p => p.Location_Id == placeToSearch.Id);
}
public void Dispose()
{
// ... Proper dispose pattern implementation excluded for brevity
if (_db != null && _db is Disposable)
((Disposable)_db).Dispose();
}
}
*This is not the best way to inject a disposable object, by the way. But it is relatively safe to do it this way and it demonstrates the principle without the extra clutter.
Now you only have one DbContext and EF will generate and maintain one single database, even though you have nice logical domain silos that can operate independently.
When you want to perform a join between the silo entities you code can use the MyDbContext class directly.

Difference between .edmx file and creating an Entities.cs file

I have looked at two of Microsoft's tutorials for MVC. In one tutorial they are creating a .edmx file to handle the Entity Framework in order to execute Linq queries. In another tutorial they made a class called "MusicStoreEntities.cs" here is the code:
using System.Data.Entity;
namespace MvcMusicStore.Models
{
public class MusicStoreEntities : DbContext
{
public DbSet<Album> Albums { get; set; }
public DbSet<Genre> Genres { get; set; }
public DbSet<Artist> Artists { get; set; }
public DbSet<Cart> Carts { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderDetail> OrderDetails { get; set; }
}
}
And the tutorial creates an instance of this class and starts doing Linq queries as well. What are the differences between these 2 methods? and how can I make DbSet objects in a .edmx file? Thank you.
There are various ways to create your model structure.
You can code POCO classes first, and create the database manually.
You can code POCO classes first, and create the database automatically using code first libraries.
You can create your database schema, and import it into a class diagram (which will supply all the models and navigation).
You can create your class diagram, and create your database schema from that.
1 and 2 create only the cs, while 3 and 4 create the edmx.
You can check this for Code First EF (this includes the DbSet part of your question).
EDIT: You can even use POCO classes with an existing database, as posted here.

Categories

Resources