Getting Table and Column Names from DbContext - entity-framework

With the new Public Mapping API what is the proper way of going from an Entity to getting the corresponding database schema and table names, and the mapping of the entities properties to column names?

Here is a reference with a ADO.NET Entity Data Model generated with Database First approach. It uses the schema provided by the connection of DbContext.
Schema Restriction is not enforced but just returns more clear results. For further information, please take a look with
https://msdn.microsoft.com/en-us/library/cc716722(v=vs.110).aspx
using (var dbContext = new DbGeneratedByEfEntities())
{
var conn = dbContext.Database.Connection;
conn.Open();
var restrictions = default(string[]);
// please replace DbName and Owner with the actual value
restrictions = new string[] { "DbName", "dbo" };
// get DataTable from schema with collection name of "Tables"
var tablesDataTable = conn.GetSchema(SqlClientMetaDataCollectionNames.Tables, restrictions);
// show column names
Debug.WriteLine(string.Join(" | ", tablesDataTable.Columns.Cast<DataColumn>()));
// show row contents, table names from schema
tablesDataTable.Rows.Cast<DataRow>().ToList().ForEach(r =>
{
Debug.WriteLine(string.Join(" | ", r.ItemArray));
});
/************************/
// please replace DbName, Owner and TableName with the actual value
restrictions = new string[] { "DbName", "dbo", "TableName" };
// get DataTable from schema with collection name of "Columns"
var colsDataTable = conn.GetSchema(SqlClientMetaDataCollectionNames.Columns, restrictions);
// show column names
Debug.WriteLine(string.Join(" | ", colsDataTable.Columns.Cast<DataColumn>()));
// show row contents, field names from schema
colsDataTable.Rows.Cast<DataRow>().ToList().ForEach(r =>
{
Debug.WriteLine(string.Join(" | ", r.ItemArray));
});
}

Related

Linq lambda query to select child and specify parent data

I have two tables, User and Group. I need to select user table and name of the group through lambda expression, and the return type of the method is User table
Below is my schema structure for user
Below is my schema structure for Group table
Try something like;
var query = yourContext.Users.Select(user => new
{
User = user,
GroupName = user.Group.Name
});

Not able to use IN query in LINQ with Entity Framework

I am using EF Framework to retrieve the data from SQL DB.
Sub Request Table looks like below:
In this table "org_assigneddept" is foreign key to another Department Table.
I have list of Departments as Input and I want to retrieve only those rows from DB whose org_assigneddept is matching the list.
Please find my whole code:-
private List<EventRequestDetailsViewModel> GetSummaryAssignedDeptEventRequests(List<EmpRoleDeptViewModel> vmDept)
{
List<EventRequestDetailsViewModel> vmEventRequestDeptSummary = new List<EventRequestDetailsViewModel>();
RequestBLL getRequestBLL = new RequestBLL();
Guid subRequestStatusId = getRequestBLL.GetRequestStatusId("Open");
using (var ctxGetEventRequestSumm = new STREAM_EMPLOYEEDBEntities())
{
vmEventRequestDeptSummary = (from ers in ctxGetEventRequestSumm.SubRequests
where vmDept.Any(dep=>dep.DeptId == ers.org_assigneddept)
select new EventRequestDetailsViewModel
{
SubRequestId = ers.org_subreqid
}).ToList();
}
}
It is giving the following error at the LINQ Query level:-
System.NotSupportedException: 'Unable to create a constant value of
type 'Application.Business.DLL.EmpRoleDeptViewModel'. Only primitive
types or enumeration types are supported in this context.'
Please let me know as how can I achieve the result
You cannot pass the department VMs to SQL, it doesn't know what those are.
// Extract the IDs from the view models.. Now a list of primitive types..
var departmentIds = vmDept.Select(x => x.DeptId).ToList();
then in your select statement...
..
where departmentIds.Contains(id=> id == ers.org_assigneddept)
..

Insert/Update data to Many to Many Entity Framework . How do I do it?

My context is =>
Using this model via Entity Framework code 1st,
data table in database becomes =>
1) User Table
2) Role Table
3) UserRole Table - A new linked table created automatically
Model for User is =>
Model for Role is =>
and my O Data query for inserting record for single User/Role table working properly
Now, what query should I write, when I want to Insert record to UserRole table
can someone have any idea
// Fetch the user.
var user = await metadataManagentClient.For<User>().FirstOrDefaultAsync(x => x.Name == "Test");
// If you want to add a new role.
var newRole = new Role()
{
Name = "My new role"
};
user.Roles.Add(newRole); // Adds new role to user.
// If you want to add an existing role
var existingRole = await metadataManagentClient.For<Role>().FirstOrDefaultAsync(x => x.Name == "My Existing Role");
user.Roles.Add(existingRole); // Adds existing role to user.
// Save changes.
metadataManagentClient.SaveChanges();
Or
await metadataManagentClient.SaveChangesAsync();
You might want to set ID as well. But watch out for new Guid() since it generates an empty guid. What you probably want (if you're not using IDENTITY) is Guid.NewGuid().

How to take database name as variable

I am creating an app for employees using Meteor and MongoDB. This app will be used by multiple organizations. So I will make a separate DB for each organization. I am facing an issue in Meteor about how to keep database name and collection name as variable. Database name will be decided on login. Then I will keep DB name in Session.
Collection name can also be a variable.
For example:
var dbName = Session.get("dbName"); //for eg dbName="redex"
var collectionName = Session.get("collectionName"); // for ex collectionName="employees"
Employees = new Mongo.Collection(collectionName);
How to manage the variables in this case?
You will have to create a server method that creates a given database according to dbName and collectionName parameters:
'newDatabase': function (dbName, collectionName) {
var d = new MongoInternals.RemoteCollectionDriver(process.env.MONGO_URL.replace("originDB", dbName));
Employees = new Mongo.Collection(collectionName, { _driver: d });
}
You will also have to declare that new collection on your client side:
Meteor.call('newDatabase', Session.get("dbName"), Session.get("collectionName"), function (err, res) {
if (!err)
Employees = new Mongo.Collection(Session.get("collectionName"));
});

querying MS Access column properties with OleDb

I'm using OLE and C#.NET to query the schema of a MS Access database. Specifically, I need to find out whether a particular column is an "identity" column or not. For SQL Server, I can use:
select COLUMNPROPERTY(object_id('dbo.tablename'),'columnname','IsIdentity')
... but when I invoke this SQL against Access, I get an OleDbException with the following message:
Undefined function 'COLUMNPROPERTY' in expression.
Searching the archives, it appears there are ways to do this with DAO, but I need to use OLE. Anyone happen to know how I can do this with OLE?
You can get the schema from the connection, for example:
cn.GetOleDbSchemaTable(OleDbSchemaGuid.Indexes,
new Object[] { null, null, null, null, "Table1" });
Is the indexes for Table1. One of the fields returned is PRIMARY_KEY
See http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbschemaguid.columns(v=vs.71)
The same using the GetSchema method.
using(OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;" +
"Data Source=C:\temp\db.mdb;" +
"Persist Security Info=False;"))
{
con.Open();
var schema = con.GetSchema("Indexes");
var col = schema.Select("TABLE_NAME = 'YourTableName' AND PRIMARY_KEY = True");
Console.WriteLine(col[0]["COLUMN_NAME"].ToString());
}