Hi is there an easy way to get the values of a foreign key, without writing sql queries.
I generated the code with the help of my mssql database (ADO.NET).
Here's an example for clarification
order table:
id customer_fk
1 100
2 105
customer table:
id name
100 Walter
105 White
view:
#model ...order
...
#customer_fk
#customer_fk delivers eg. "100" instead of "Walter"
Not sure if you are required to use ADO.NET, but to accomplish what you want, without writing sql, you'll need to use some kind of ORM, such as EntityFramework.
You will need to write LINQ, which generates SQL and since EF will know about the relationship between the two tables, you will have access to the "name" property in the customer table.
Linq to SQL might be a good option, since you're using MS SQL. Just add the DataContext item to your project, and drag/drop the tables from your server. Then you should be able to write something like:
public ActionResult Order(int orderId)
{
using (MyDataContext context = new MyDataContext())
{
var loadOptions = new LoadOptions();
loadOptions.LoadWith<order>(o => o.customer);
context.LoadOptions = loadOptions;
var theOrder = context.orders.Where(order => order.id == orderId).FirstOrDefault();
return View(theOrder);
}
}
But if you're already using ADO.Net, maybe just write the query? It's not that difficult:
SELECT order.*, customer.name
FROM order INNER JOIN customer ON order.customer_fd = customer.id
If you're doing this in Entity Framework (or some other similar ORM), you can write a LINQ query that joins to your foreign key table:
var customerOrders =
from o in context.Orders
join c in context.Customers on o.customer_fk equals c.ID
select new { OrderID = o.ID, CustomerName = c.Name };
Related
I have a LINQ query like this:
var data = from user in _context.Users
select new
{
UserId = user.Id,
Username = user.UserName,
RoleNames = (from userRole in _context.UserRoles
join role in _context.Roles on userRole.RoleId
equals role.Id
where userRole.UserId == user.Id
select role.Name).ToList()
};
if (!string.IsNullOrEmpty(searchText))
data = data.Where(x => x.Username.Contains(searchText) || x.RoleNames.Any(r => r.Contains(searchText)));
The result are something like this:
User Id | Username | RoleNames
1 | Matt | [User, Admin]
2 | Jennifer | [User]
3 | John | []
But the
x.RoleNames.Any(r => r.Contains(searchText))
is not working, it's causing InvalidOperationException: The LINQ expression '...' could not be translated.
I want to pass in a searchText to search for either "Username" and "RoleNames" columns.
E.g. if I pass in searchText = 'Jen' it will return User Id 2, and if I pass in searchText = 'user' it will return User Id 1 and 2.
Any help would be appreciated.
While theoretically it is possible to translate this condition to the SQL, your EF Core version do not supports that. Consider to make filter before defining custom projection:
var users = _context.Users.AsQueryable();
if (!string.IsNullOrEmpty(searchText))
users = users.Where(x => x.Username.Contains(searchText) || x.Roles.Any(r => r.Contains(searchText)));
var data =
from user in users
select new
{
UserId = user.Id,
Username = user.UserName,
RoleNames = (from userRole in _context.UserRoles
join role in _context.Roles on userRole.RoleId
equals role.Id
where userRole.UserId == user.Id
select role.Name).ToList()
};
This may not be the answer you want now but you'll probably look back on this and see it as the right answer later.
Your ORM (Probably Entity Framework) can't translate your Linq Expressions into a query. If your project will have a small database and you don't need your queries to perform well then, tweak your expression so that the ORM can generate a functioning, albeit sub-optimal, query.
If data will be a significant part of your project then switch to a light ORM like Dapper and learn the query language of your database. Write optimal, parameterised queries in that query language and yield the long term benefits.
How to query range key programmatically in DynamoDB, I am using .Net AWSSDK ,I am able to query on Hash key with below code :
GetItemRequest request = new GetItemRequest
{
TableName = tableName
};
request.Key = new Dictionary<string,AttributeValue>();
request.Key.Add("ID",new AttributeValue { S = PKValue });
GetItemResponse response = client.GetItem(request);
Please suggest,
Thanks in advance.
There are two kinds of primary key in DynamoDB: Hash-only or Hash-Range.
In the above code I guess your table is Hash-only and you use the hash key to retrieve an element with hashkey equals to PKValue.
If your table is in H-R schema and you want to retrieve a specific element with a hashKey and rangeKey, you can reuse the above code and in addition, add the {"RangeKey", new AttributeValue } into your your request.KEY
On the other hand, query means a different thing in DynamoDB. Query will return you a list of rows sorted in some order.
I am using lightswitch and i have to join 3 tables in my query. Table A join Table B join table C where tableC.id == 10
partial void Query2_PreprocessQuery(int? dept, ref IQueryable query)
{
query = query.Join(Employee_Personal_Infoes, b => b.Employee_Personal_Info1.Emp_id, (b));
}
First off, if you add relationships between your tables, you shouldn't ever need to do manual joins. You would then just use the navigation properties that get created when you add the relationships.
Second, you can't change the shape of the entity in a query, or return a set of different entities. If your query is based say on a Customer entity, you can't return a query of CustomerAdresses, or a Client entity from that query. The query can only return a filtered set of the same entity that the query is based on.
Does that make sense?
I have 2 tables.
Users - have userID, userMainGroup and userMinorGroup
Tasks - TaskId, UserId
My goal is:
I have current CurrentuserId and i want to show him all the tasks that were created by users from the same MainGroup as he.
In SQL i would write:
Select *
From Tasks Left join Users on tasks.Id=users.id
Where users.MainGroup=CurrentuserMainGroup; (var)
How do i do it using entity framework?
I understood that to make a join i need to write something like:
var tasks = from t in db.tasks
from u in db.users
where t.Id=u.Id
select new {t.Id, t.name....}
but where do i put the condition Where on the MainGroup?
you can try like this
var data= (from con in db.tasks
let UserMainGroup = db.users.where(x=>x.id==con.id).FirstOrDefault()
where UserMainGroup.MainGroup=CurrentuserMainGroup
select new {
ID=con.id,
Name=con.name
}).ToList();
i think this will help you.......
It is recommended that you use navigation properties in stead of manually coded joins:
from t in db.Tasks
where t.User.MainGroup == currentuserMainGroup
select new {t.Id, t.name.... , t.User.Name, ... }
Hi i have written one linq query to fetch records from entity model. I am getting perfect number of records but all are same.
here is my query
Entities.TEST.Where(a => a.ID.ToUpper().Equals(ID.ToUpper())).OrderBy(s => s.NAME).ToList();
Am I missing something?
You need to make sure your Entity Key in your Entity Data Model is unique.
So in your example, ID should be the entity key for your Test entity
Your query should work, i have a similar sample that works for northwind DB:
var ctx = new NorthwindEntities();
var emp = ctx.Employees.Where(e => e.TitleOfCourtesy.Equals("ms.", StringComparison.OrdinalIgnoreCase)).OrderBy(n => n.FirstName).ToList();
Please check your query in LinqPad. You will see the results and the generated SQL.
Replace Equals with == and you can go