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?
Related
I would like to know what the best way is to create a custom lookup for a field in my table, my situation is as following:
I have Form A which has a datasource to Table A, a field on that datasource has a lookup method:
public void lookup(FormControl _formControl, str _filterStr)
{
changeCompany(companyInfo.DataArea)
{
super(_formControl, _filterStr);
}
}
The field has an EDT, which has an relation to a Table.
The table has multiple fields, 1 of them is field: GroupType (Enum), with 2 options: Suppliers and Customers.
Form A is showing all records, both with Suppliers and Customers, but i would like to filter on the records with only has the value Suppliers in Column C.
Based on the information above, what is the best way to create this custom lookup?
You can create Related field fixed relation between your tables
TableB = TableB.Id
Enum::Suppliers = TableB.GroupType
Or create a custom lookup
and set a range for field GroupType.
All,
I have an entity, that has several collections,- each collection is mapped lazily. When I run a criteria query, I get duplicate results for my root entity in the result set. How's that possible when all my collections are mapped lazily!
I verified, my collections, load lazily.
Here's my mapping:
Root entity 'Project':
[Bag(0, Lazy = CollectionLazy.True, Inverse = true, Cascade = "all-delete-orphan")]
[Key(1, Column = "job_id")]
[OneToMany(2, ClassType = typeof(ProjectPlan))]
public virtual IList<ProjectPlan> PlanList
{
get { return _planList; }
set { _planList = value; }
}
The criteria query is:
ICriteria criteria = session.Session.CreateCriteria<Entities.Project>()
.Add(Restrictions.Eq(Entities.Project.PROP_STATUS, !Entities.Project.STATUS_DELETED_FLAG));
.CreateAlias(Entities.Project.PROP_PLANLIST, "p")
.Add(Restrictions.Eq("p.County", 'MIDDLSEX'))
.setFirstResult(start).setMaxResults(pageSize)
.List<Entities.Project>();
I know, I can correct this problem w/ Distinct result transformer, I just want to know if this is normal behavior on lazy collections.
EDIT: I found the cause of this,- when looking at the raw SQL, the join, and where clause are correct but what baffles me is the generated Select clause,- it not only contains columns from the project entity (root entity) but also columns from the project plans entity which causes the issue I described above. I am not at work right now, but I'll try to do this: .SetProjection(Projections.RootEntity()), so I only get Project's columns in the select clause.
One way, how to solve this (I'd say so usual scenario) is: 1) not use fetching collections inside of the query and 2) use batch fetching, as a part of the mapping
So, we will always be querying the root entity. That will give us a flat result set, which can be correctly used for paging.
To get the collection data for each recieved row, and to avoid 1 + N issue (goign for collection of each record) we will use 19.1.5. Using batch fetching
The mapping would be like this
[Bag(0, Lazy = CollectionLazy.True
, Inverse = true
, Cascade = "all-delete-orphan"
, BatchSize = 25)] // Or something similar to batch-size="25"
[Key(1, Column = "job_id")]
[OneToMany(2, ClassType = typeof(ProjectPlan))]
public virtual IList<ProjectPlan> PlanList
{
...
Some other similar QA (with the almost same details)
How to Eager Load Associations without duplication in NHibernate?
NHibernate QueryOver with Fetch resulting multiple sql queries and db hits
Is this the right way to eager load child collections in NHibernate
And we still can filter over the collection items! but we have to use subqueries, an example Query on HasMany reference
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 };
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
how to implement Left outer join in Linq to entity framework. DefaultIfEmpty function is not supported.
please provide an example.
This works in .NET 3.5. When you join without doing "from" in combination with the FirstorDefault function, it will give you the row you are looking for in the left joined table. If you want multiple rows, just use where() instead.. Hope this helps.
====
comments = from p in _db.Master
join t in _db.Details on p.DetailID equals t.DetailID into tg
select new
{
A = p.Column1,
//this next column is the one from the left joined table
B = tg.FirstOrDefault(t => t.DetailID == p.DetailID).Column2
};
Entity framework in .NET 3.5 doesn't offer left join in Linq queries. The way to get "joined records" is through navigation property between entities. Something like:
var query = from u in context.Users
select new
{
User = u,
Orders = u.Orders.Where(...) // Filtered left join but User and Order must be related
};