Hi I have a question that is braking my mind for some days.
I have my SQL server Database and my C# application.
In the DB I have differemt tables, let me show you a simple ex
Tables:
Person
Relationship
City
Business Rules:
The person are from a City, so the person has IdCity
A person has a relationship with other person, and about that relationship you need to save the starting date.
In other projects I already did something like that, but in this proyect this is not working for me.
When I retrieved with LinQ the information about the person, the city is not coming, and an error appears when I try "person.city.description", for ex.
I try using Include("City") in the linq query, but it didn't work. Besides that, I don't know how to manage the circular reference to the person to person relationship.
One important thing, that I think that can be the problem, is that I rename all the tables from the DataModel, for example, the table in database is called Prd_City, so I change the Name and the Entity Set Name for City in c# project. So in the included I have to use the real table name, in other case the query fail, but if I use the real name nothing happens.
using (var context = new MyContext())
{
List<Person> oPeople = (from p in context.Person.Include("Prd_City")
select p).ToList();
return oPeople ;
}
Any help will be welcome.
Thanks!
"It didn't work" is never a good description of your problem. But from the rest of your question I can infer that Person has a navigation property named "Prd_City", while you expected it to be "City". The thing is: you renamed the entities, but not the navigation properties in the entities.
My advice (for what it's worth): it seems that your work database-first. If you can, change to code-first and manually map the POCO classes to their table names, and properties to their database columns. It may be a considerable amount of work (depending on the size of your data model), but after that you will never run the risk of EF "un-renaming" your entities. Besides, the DbContext API is easier to use than ObjectContext. Currently, it's the preferred EF API.
Related
I have a generic group members table with a GUID for a "group type" and a GUID for "referenced object". An example would be if I have a table of customers(each having a GUID) I can group them under "already paid" by creating a group GUID and in my "Group members table" referencing every customer by their respective GUID. This allows for any type of group to be added to the model as we expand(without adding extra tables).
Here is the problem. I have created a subquery in an entity in order to filter the universal group members table for a certain group and what "items" are and are not in that group; like so:
partial void ElementsNotMemberOfGroup_PreprocessQuery(int? UniversalGroupTypeIDParameter, int? UniversalGroupsIDParameter, ref IQueryable<UniversalGroupMember> query)
{
query = query.Where(x => x.UniversalGroup.UniversalGroupType.UniversalGroupTypeID == UniversalGroupTypeIDParameter);
query = query.Where(x => x.UniversalGroup.UniversalGroupsID != UniversalGroupsIDParameter);
}
This returns the GUIDs for the referenced object in the group, but for a user that's useless. I need to join this table and my customers table at runtime on the GUID so I can extract the customer info and display it.
Any Ideas?
LightSwitch wasn't really created with this kind of scenario in mind. LightSwitch makes things very easy for you when you create relationships between tables that are, well, "related". When you do this, you never need manual joins between entities.
While it's possible to do something similar to what you're describing (see the link below), it's a lot more work to achieve it, and in my opinion it isn't really worth the extra trouble. Not only that, but as you're discovering, it complicates even the most simple operations.
In essence, you're working against LightSwitch, instead of with it. My advice to you would be that if you really must do this type of manual optimization, then LightSwitch may not be the best product for you to use.
Beth Massi has a blog article, Using Different Edit Screens Based on Record Types (Table Inheritance), which isn't exactly what you're doing, but it may give you some ideas if you decide to still use LightSwitch for your project.
Let's say I have three tables:
Office
ID
SalespeopleOffice
ID
OfficeID
PersonID
People
ID
ManagerID
In LINQ to SQL, how can I start from the SalespeopleOffices table and "walk" from that table to the People table or the Office table via the relationships between the tables? Specifically without knowing what those relationships are; pull the data about the relationships instead of interacting with the objects directly. I'm looking for a way to programatically analyze table relationships. The database I'm working with has many more tables than this, so in reality it's a lot more complex than this.
I'd ideally like to create a LinqPad script to do this.
You can use reflection to examine the properties on each type in the context. (In LinqPad, the context is this).
Value and string properties will be scalar fields on the table,
EntitySet properties will represent [something]-to-many relationships, and
other types will be [something]-to-one relationships.
If you connect the two sides of the relationships you can figure out what the [something] is in each case. Does that make sense?
Edit
I was just poking around a little, and there's a better approach. The model information is available via the Mapping property. Try this:
var tableData = from t in this.Mapping.GetTables()
select new
{
t.TableName,
Associations =
from a in t.RowType.Associations
select new
{
a.ThisMember.Name,
TypeName = a.ThisMember.Type.Name
}
};
tableData.Dump();
Assuming you've activated Auto Completion, it should be a piece of cake to find the exact data you're interested in by exploring the properties on this meta data.
If you're using LINQ to SQL, your SalespeopleOffices instances shoud have People and Office properties.
Something like:
var salesPO = dataContext.SalespeopleOffices.First()
var office = salesPO.Office
var man = salesPO.People
Suppose I have an automatically-generated Employee class based on the Employees table in my database.
Now suppose that I want to pass employee data to a ShowAges method that will print out name & age for a list of employees. I'll retrieve the data for a given set of employees via a linq query, which will return me a set of Employee instances. I can then pass the Employee instances to the ShowAges method, which can access the Name & Age fields to get the data it needs.
However, because my Employees table has relationships with various other tables in my database, my Employee class also has a Department field, a Manager field, etc. that provide access to related records in those other tables. If the ShowAges method were to invoke any of those methods, this would cause lots more data to be fetched from the database, on-demand.
I want to be sure that the ShowAges method only uses the data I have already fetched for it, but I really don't want to have to go to the trouble of defining a new class which replicates the Employee class but has fewer methods. (In my real-world scenario, the class would have to be considerably more complex than the Employee class described here; it would have several 'joined' classes that do need to be populated, and others that don't).
Is there a way to 'switch off' or 'disconnect' the Employees instances so that an attempt to access any property or related object that's not already populated will raise an exception?
If not, then I assume that since this must be a common requirement, there might be an already-established pattern for doing this sort of thing?
maybe not the answer you're looking for,but how about projecting the results of your query into a more light-weight POCO, eg:
var employeePOCOs = from e in l2sEmployees
select new EmployeePOCO
{
Id = e.Id,
Name = e.FirstName + " " + e.LastName
};
where EmployeePOCO is a predefined class
would that help? I've used this when returning Entity Framework objects back through an AJAX call where the output was going to JSON, and it seemed to do the trick.
One way to do this is to 'detach' the entity from its database context. Take a look at an answer I gave to a similar question. It shows you a couple ways of detaching entities.
I have three tables Projects, Users and ProjectMembers. The ProjectMembers table is a mapping table and has only two columns ProjectId and UserId.
In my object model i have two classes Project and User. The Project class has a property IEnumerable<User> Members
I am using an external xml map file for mapping linq to sql associations. I am able to get the Project and the User data but I dont know how to map the Members association.
This sounds like a Many-to-Many mapping (Projects <-> Users).
In which case you are going to run into problems using Linq To SQL. To cut a long story short it does not really support that mapping. There are several workarounds which you can find on google, one of which is altering the partial class to provide the access to the Members/Projects collection on the Project and User classes respectively.
e.g. http://www.iaingalloway.com/2015/06/many-to-many-relationships-in-linq-to-sql.html
I'm using Linq 2 Sql and I'd like to add a custom member on one of my data type. For example: I have tables Companies, Departments and Employees. Departments has a FK in Companies and Employess has a FK in Deparments. Very simple.
My goal is to add an EmployeeCount property on Company that will, of course, returns the number of employee in the company (by suming the number of employee in company's departments).
As you may know, it's really trivial to do: just add a member on the partial class and do the stuff. The problem is, I now want to sort on this custom member.
How can I write this custom member for Linq to be able to translate the logic into a valid SQL orderby? I tried with a SPROC but did not success.
Any help appreciated!
Fabian
I guess your may need to add this column to your schema, in order for SQL server to recognize it and take in under consideration in his optimizations.
I would have add a trigger that will update this column automaticly upon changes on your data.