0

I am new to Entity Framework with ASP.NET MVC and C#. I need to create the small demo for crud operation using Entity Framework and in the backend, I have used SQL Server. I have to create 2 databases:

  1. Employee
  2. EmployeeUsers

In database Employee I have one table, Sectors.

Here below I have shown my table data.

ID | Sector_name | UserId
1     Private       1
2     Business      2

In database EmployeeUsers I have also one table, users.

This is the sample data for users:

ID | FName | LName
1    ABC     P
2    XYZ     x

Now using Entity Framework, I need to work with 2 databases but how can do that I have no idea anyone know then please let me known.

This is my expected o/p:

ID | SectorName | UserFname
 1    Private       ABC
 2    Business      XYZ
Edit
  • 29
  • 1
  • 3
  • 9
  • Try creating two edmx for those databases. And ge the user id from employee database and use those ids to get the data from the employee users database – imanshu15 Mar 07 '18 at 05:35
  • @imanshu15 you mean I need to create 2 different database using 2 edmx and in the controller i need to create 2 object for 2 diff edmx? can you please give me little bit more details on that point – Edit Mar 07 '18 at 05:37
  • @imanshu15 how can show list of the sector table with the username.? any idea? – Edit Mar 07 '18 at 05:41
  • Possible duplicate of [Configure multiple database Entity Framework 6](https://stackoverflow.com/questions/20308378/configure-multiple-database-entity-framework-6) – Gaurang Dave Mar 07 '18 at 05:44
  • possible duplicate of https://stackoverflow.com/questions/20308378/configure-multiple-database-entity-framework-6 and https://stackoverflow.com/questions/17941225/using-entity-framework-on-multiple-databases and – Gaurang Dave Mar 07 '18 at 05:45
  • Check this http://olivierhelin.com/blog/entity-framework/entity-framework-6-one-entity-data-model-multiple-databases-2 – Gaurang Dave Mar 07 '18 at 05:45
  • @GaurangDave Ok, I will check thank you' – Edit Mar 07 '18 at 05:47
  • Why you can't create a view where you use multiple database join query and use the view to query inside EF ? – Bimal Das Sep 15 '22 at 07:37

2 Answers2

2

What you can do is, use two entity framework database contexts for each database with their database connection string.

Creating the database context depends on the entity framework development model you choose. (Code first or Database first)

Database first:

Create edmx file for both databases. If you want to know how to create it, check out this Microsoft Link

Code first

the model for Employee database

public class Sector
{
   public int ID {get; set;}
   public string Sector_name {get; set;}
   public int UserId {get; set;}
   // you can't use Users class for navigation purpose because Users is in different context
}

So for Employee database you can use this database context

public partial class EmployeeContext : DbContext
{
    public EmployeeContext()
        : base("name=EmployeeDatabaseConnectionString")
    {
    }
    
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }
    
    public virtual DbSet<Sector> Sectors { get; set; }
}

the model for EmployeeUser database

public class User
{
   public int ID {get; set;}
   public string FName {get; set;}
   public string LName {get; set;}
}

for EmployeeUser database, use the following database context

public partial class EmployeeUserContext : DbContext
{
    public EmployeeUserContext()
        : base("name=EmployeeUserDatabaseConnectionString")
    {
    }
    
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }
    
    public virtual DbSet<User> Users { get; set; }
}

The tricky thing in code first is, you have to handle the migration for both database contexts. If you want to know how to do that, check out this SO answer.

Now you can do anything using the Database context. For your question on the comment, on how you can show a list of the sector table with the username....... I don't see a UserName column on the Users table.

Assuming that UserName is FName and assuming sector's user id are in sync with users table id.

The answer to your question could be:

Since both tables are in a different context, and Entity framework context does not support cross-database queries; you have to write two LINQ queries.

example:

UserName: ABC

EmployeeContext employeeContext = new EmployeeContext();
EmployeeUserContext employeeUserContext = new EmployeeUserContext();

// get the user
var user = employeeUserContext.Users.FirstOrDefault(u => u.FName == "ABC");

// get sector list
var sectors = employeeContext.Sectors.Where(s => s.UserId == user.Id);

UPDATED:

var employeeContext = new EmployeeContext();
var employeeUserContext = new EmployeeUsersContext();
            
var users = employeeUserContext.Users.ToList();
var sectors = employeeContext.Sectors.ToList();

var yourTask = from user in users
               join sector in sectors on user.ID equals sector.UserId
               select new {sector.ID, sector.SectionName, user.FName};
ash
  • 2,902
  • 3
  • 19
  • 34
  • Suppose I need to get all sector list with username belongs to user id then how can do that?your solution's absolutely correct. can you please give me hint. – Edit Mar 07 '18 at 06:27
  • I thought that was the question that you asked before. – ash Mar 07 '18 at 06:33
  • so where is the user name? Which database table is it in? – ash Mar 07 '18 at 06:36
  • see my expected o/p in the post. – Edit Mar 07 '18 at 06:38
  • what you can do is make a linq join between users and sectors. To do that, you have to query all the users, then all the sectors and inner join them by user id. From their, select what you want in your case ID, SectorName, and UserFName. – ash Mar 07 '18 at 06:44
  • I am going to join I am got this error "The specified LINQ expression contains references to queries that are associated with different contexts." – Edit Mar 07 '18 at 07:26
0

If you have two databases then create two edmx. This will provide you with two connection strings in your app.config which contains the name to the context classes to use. Notice that using statements are using two different contexts.

public class DataAccess
{
    public int GetUserIdByUserName(string username)
    {
        using (var context = new EmployeeUsersEntities())
        {
            var user = context.Users.First(d => d.Name == username);
            return user.Id;
        }
    }

    public string GetSectorByUserId(int id)
    {
        using (var context = new EmployeeEntities())
        {
            var sector = context.Sectors.First(d => d.UserId == id);
            return sector.Sector_name;
        }
    }
}

If you have one database containing the two tables, then create one edmx and you will have one connection string and one context class.

Michael.Ha
  • 21
  • 3