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.
Related
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
The main problem is that when the web app is launched to the internet, when the load is high an exception is raised telling that there is already an opened data reader.
The following are the specs we use:
Entityframework 5.0.0
MySQL database
Is there a way of solving this problem without the using(){} block? Main problem of this approach is that when closed the using block I can't expand foreign key relations of entityframework objects inside the html view.
I also attach some source code, showing how we keep a single database context through the whole application
public abstract class AbstractService
{
public Entities db_model
{
get
{
return DbContext.Instance.db_model;
}
}
}
public class DbContext
{
public Entities db_model = new Entities();
private static DbContext _dbContext;
public static DbContext Instance
{
get
{
if(_dbContext == null)
{
_dbContext = new DbContext();
}
return _dbContext;
}
}
}
This answer is specifically related to the issue mentioned in the question about using the loaded entities in an ASP.NET View. The question asks about a way of solving this problem without a using block or disposing of the DbContext, however I am suggesting doing exactly this.
The reason being that it's generally desirable not to use Entity Framework objects in the ASP.NET Views because those objects are a lot more more than just plain POCO objects; they hide logic which allows them to act as a proxy to the underlying database, so they have a hidden dependency on the state of the DbContext which created them.
Here's a contrived example using EF models for Employee and Department with a DbContext:
public class CompanyDbContext : DbContext
{
public DbSet<Department> Departments { get; set; }
public DbSet<Employee> Employees { get; set; }
}
public class Department
{
public long Id { get; set; }
public virtual ICollection<Employee> Employees { get; set; }
}
public class Employee
{
public long Id { get; set; }
public long DepartmentId { get; set; }
public virtual Department Department { get; set; }
}
If these were used in an ASP.NET application, I would create some separate models which aren't tied to Entity Framework, to be used by ASP.NET. For example:
public class DepartmentModel
{
public long Id { get; set; }
public List<EmployeeModel> Employees { get; set; }
}
public class EmployeeModel
{
public long Id { get; set; }
public long DepartmentId { get; set; }
}
A few considerations:
According to the MSDN docs, "A DbContext represents a combination of the UnitOfWork and Repository patterns" - https://learn.microsoft.com/en-us/dotnet/api/system.data.entity.dbcontext?redirectedfrom=MSDN&view=entity-framework-6.2.0 - Therefore the DbContext should be short lived as far as possible.
When loading data from the context, related entities can be retrieved using DbSet<>.Include() - https://learn.microsoft.com/en-us/ef/ef6/querying/related-data
Generally speaking, it makes sense to de-couple the 'data' layer from the 'view' layer - for all kinds of reasons, some of which are listed here: https://learn.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/part-5 -- this involves mapping between the EF objects and the POCO Models.
The logic which is used to query the DbContext would query the data using EF, and return that data using POCO models so that only logic which deals directly with DbContext has any involvement with the EF objects. For example:
public List<DepartmentModel> GetAllDepartments()
{
using (var ctx = new CompanyDbContext())
{
// Ensure that related data is loaded
var departments = ctx.Departments
.Include(d => d.Employees);
// Manual mapping by converting into a new set of models to be used by the Views
var models = departments
.Select(d => new DepartmentModel
{
Id = d.Id,
Employees = d.Employees
.Select(e => new EmployeeModel
{
Id = e.Id,
DepartmentId = e.DepartmentId
})
.ToList(),
})
.ToList();
return models;
}
}
Being able to use those POCO models, while requiring some extra boilerplate code, provides complete separation between the DbContext and ASP.NET, allowing the data to be used without ASP.NET Views/Controllers being concerned by the lifetime or state of the DbContext.
Sometimes this may look as if this approach violates the 'DRY' principle, however I would point out that EF objects and ViewModel objects exist to solve different problems, and it's not uncommon for the ViewModel objects to take a different shape, or even to require additional fields/attributes which wouldn't be suitable to add to the EF classes.
Lastly, the above uses 'manual' mapping, but if the mappings are really simple and straightforward, then it could make more sense to use AutoMapper instead: Cleanest Way To Map Entity To DTO With Linq Select?
Being new to ASP .NET I've been researching on entity modeling approaches and it seems ORM using Entity Framework following Code First is the best approach for me.
By following this tutorial, I have gotten the impression that, for each entity, you need to create a connectionstring (correct me if I'm wrong) and this fact confuses me when it comes to relational data, as, per this example, the database itself seems to cover just one entity. So how is relational data handled in the EF.
PS: For unification purpose, please use entities Movies, Customers and the relational table named under the proper naming conventions.
You create a connection string per DbContext. Here is the class that defines the DBContext:
public class MovieDBContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
}
To add more tables to this context, add more lines like this (for examples, public DbSet<Customer> Customers { get; set; }.
public class MovieDBContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
public DbSet<Ticket> Tickets { get; set; }
}
Accessing these from a context:
public class TicketController {
private MovieDBContext db = new MovieDBContext ();
public ActionResult Index(int movieId) {
var listOfTickets = db.Tickets.Where(t=>t.MovieId == movieId).ToList();
var parentMovie = db.Movie.Where(m=>m.Id == movieId).Single();
...
}
}
Connection String: Contains initialization information that is passed as a parameter from a data provider to a data source.
You need a new connection string each time you are connecting to something different (You can have two different DBContexts using the same ConnectionString), in this tutorial although the Data Source of both connection strings is the same, the AttachDbFileName is different.
When each DbContext is initialized, it will use one of those connection strings. In this tutorial, the first connection string (Default Connection) is used for membership (user accounts and such) and the other connection string is used for your MovieDBContext, and will contain Movies and other things as you progress in the tutorial.
It's also possible to have them both in the same database.
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.
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.