I was able to get the columns names by using this:
var props = typeof(FMCSA_NPR).GetProperties();
But it is also giving me the names of other tables which have a foreign relation with the specified table.
Is there a way by which I can only get the column names? What do we call column names when referring table as entity in Entity Model?
You can list the non-navigation properties of entities by accessing the conceptual model (CSpace):
var oc = ((IObjectContextAdapter)db).ObjectContext;
var cs = oc.MetadataWorkspace.GetEntityContainer(oc.DefaultContainerName,
DataSpace.CSpace);
foreach (var entitySet in cs.EntitySets)
{
var props = string.Join(",", entitySet.ElementType.Properties);
Trace.WriteLine(string.Format("{0}: {1}", entitySet.Name, props));
}
(Where db is your DbContext object).
Related
What is EntityReference and QueryExpression? Please give me some simple examples.
EntityReference
It is used for lookup fields in
365 – e.g. to link records via a 1 to many relationship. The lookup
field is shown on the ‘child’. You need to specify the ‘parent’ entity
type and record id.
For example if you are creating a accountand want to set the primary contact.
Entity account = new Entity("account");
account["name"] = "James Account";
account["primarycontactid"] = new EntityReference("contact", contactId);
service.Create(account);
QueryExpression
QueryExpression provides an object model to construct a query. Queries
can also be created using FetchXML, a proprietary XML based query
language.
For example of you wanted to retrieve all contacts full name and telephone number.
QueryExpression query = new QueryExpression()
{
Distinct = false,
EntityName = Contact.EntityLogicalName,
ColumnSet = new ColumnSet("fullname", "address1_telephone1"),
};
DataCollection<Entity> entityCollection = _service.RetrieveMultiple(query).Entities;
I am trying to update a 'Name' DataColumn based on a 'ID' DataColumn in a DataTable.
The 'ID'-'Name' pairs are stored in a Dictionary, which is created using a DataTable extension method as follows:
public static Dictionary<object, object> ToDictionary(this DataTable dataTable, string keyColumn, string valueColumn)
{
Dictionary<object, object> resultDict = new Dictionary<object, object>();
if (dataTable.Columns.Contains(keyColumn) && dataTable.Columns.Contains(valueColumn))
{
foreach (DataRow dr in dataTable.Rows)
if (resultDict.ContainsKey(dr[keyColumn]) == false)
resultDict.Add(dr[keyColumn], dr[valueColumn]);
}
return resultDict;
}
I am using the following LINQ syntax to update the DataColumn:
misUserDetailsDT.AsEnumerable().ToList().ForEach(row => row.SetField("DepartmentName", deptDict[row["DepartmentID"]].ToString()));
Here 'misUserDetailsDT' is the DataTable containing a filled column 'DepartmentID' and an empty column 'DepartmentName'-which I am trying to update.
I have a seperate method which generates the Dictionary as follows:
var deptDict = departmentDT.ToDictionary("DeptID", "DeptName");
where 'departmentDT' is a DataTable containing columns 'DeptID' and 'DeptName'.
Now when I execute the Linq code it give a 'KeyNotFoundException'. I have thoroughly checked that the 'departmentDT' table as well as 'deptDict' have all the keys(departmentIDs) from the 'misUserDetailsDT' table. Actually the 'departmentDT' itself has been generated from all the distinct IDs of 'misUserDetailsDT' table.
I think there is some issue with figuring out the appropriate type of the Dictionary keys. I even tried casting it to Int16, but it didn't work out.
Please help me figure out a solution.
I have figured out the problem. The code works when dictionary values are casted to Int32. Thanks to #TimSchmelter for giving a very useful info. I will be changing the code to make use of foreach loop instead.
I have database CarsDB, with Table Car in it. I whant to see the car table, but getting only System.Data.Objects.ObjectSet`1 instead of database table
public CarsBDEntities db = new CarsBDEntities();
public ActionResult Index()
{
ViewBag.Carlist = db.Cars.ToString();
return View();
}
I have make a table, then created a model from it. Using entity frameworkd and ado.net.
You don't want to use ToString; if you just return db.Cars instead, that will give you an IEnumerable that you can work with.
var cars = db.Cars;
return View(cars);
You can use this to make a Webgrid that will display your data. Razor view:
#model IEnumerable<Namespace.Models.Cars>
#{
var grid = new WebGrid(Model);
}
#grid.GetHtml()
You're trying to convert an ObjectSet to a string, which is why your getting "System.Data.Objects.ObjectSet". You'll need to pull the data out of the table to view it. For instance, something like:
string firstCarMake = db.Cars.FirstOrDefault().Make.ToString();
I have these two tables in MySql:
[Person]
PersonId
NameFirst
NameLast
[Email]
EmailId
PersonId
EmailAddress
In VS2010, I added a new item, ADO.NET Entity Data Model. I connect to MySql and "drag-and-drop" my the two tables into the .edmx designer. Great! It has relationships and all.
Now I want to bind something like this to a Gridview WITHOUT using an EntityDataSource control:
SELECT * FROM Person INNER JOIN Email ON Person.PersonId = Email.PersonId
How am I to do this programmatically using the modern approach? I noticed in my .edmx, the tables have "Navigation Properties" and the related tables are listed there. I just don't know the concept and syntax to use it since my skills are still "DataSet-SQL Queries-DataAdapter" based.
You can start with something like this:
var query = from x in Context.Persons // Entity set on your context
from y in x.Emails // Navigation property
select new PersonProjection // Your custom class for flattened result
{
PersonId = x.PersonId,
FirstName = x.NameFirst,
LastName = x.NameLast,
EmailId = y.EmailId,
EmailAddress= y.EmailAddress
};
gridView.DataSource = query.ToList();
gridView.DataBind();
I need to be to create an entity data model in the EF version 1, because my web host doesn't have Framework 4.0 yet. Below is just a simple example to show the problem.
I have 3 tables, one Users table, another Webpages table, and one table with Visits. The former two tables each have a one-to-many relationship with the Visits table (which basically works as a many-to-many relationship, only the Visits table has its own primary key and extra fields)
With the 4.0 version this works, but it doesn't with v.1. "Visits" has a count of 0, so the test string returns ""... Why, and how would I be able to access the foreign key relation in v.1?
UsersEntities context = new UsersEntities();
var users = context.Users;
string result = "";
foreach (var user in users)
{
foreach (var visit in user.Visits)
{
result += visit.Webpage.Url + "\n";
}
}
So the foreach loop loops through the users, which it gets ok, but the inner loop is never entered because there are no Visits returned. Again, in Framework 4.0 it works fine, using the same database.
So what's wrong?
Simply change your code to this:
UsersEntities context = new UsersEntities();
var users = context.Users.Include("Visits");
string result = "";
foreach (var user in users)
{
foreach (var visit in user.Visits)
{
result += visit.Webpage.Url + "\n";
}
}
Notice the Include(...) that tells EF to eagerly load each User's visits.
With that in place it should work.
Actually if Webpage is a navigation too, you might need:
Include("Visits.Webpage");
Hope this works