I am trying to access tables in entity framework using another table, but i am getting tables as null.
e.g.
I am having 3 tables A,B and C. And A is having FK(Foreign key) of B and B is having FK of C. I am having object of A. Now I want to access C using B.
means A.B.C.
But i am getting B as null. So please give me the solution for this.
var a= databaseContext.A.Find(Id);
var c=a.B.C.where(x=>x.Id==SomeId);
Thanks in advance.
Update:
Tables
Commitment
CommitmentId(PK)
FinancialYearAccountID(FK)
FinancialYearAccount
FinancialYearAccountId (PK)
AccountId(FK)
Account
AccountId(PK)
Now i want to access Account table from Commitment table
var commitment = databaseContext.Commitments.Find(1);
var account = commitment.FinancialYearAccount.Account.
where(x => x.AccountId==SomeId)
I am getting Commitment Record, but FinancialYearAccount is coming as null, so it is crashing here.
Related
I'm trying to read data from related tables which are x levels deep and which have relationships specified, i.e.:
table A
table B
table C
table ABC
Table ABC has relationships ABC.a = A, ABC.b = B and ABC.c = C,
i.e. foreign keys ABC.aid = A.id, ABC.bid = B.id and ABC.cid = C.id.
aid, bid and cid in ABC are set unique using UniqueContstraint
relationship is using lazy="joined"
When I do select(ABC) I'm able to get all values from ABC and also from related tables, i.e.:
{ABC.a: {A}, ABC.b: {B}, ABC.c: {C}}
I have also table D which has a relationship to ABC (D.abcid = ABC.id) and I struggle to construct a correct select statement which would give me all data also from A, B and C. Actually I'm not sure if this should work or I missed / do not understand something in the documentation as I have tried various loading strategies, specified join_depth for D and ABC tables, etc. No matter what I'm getting:
sqlalchemy.exc.InvalidRequestError: The unique() method must be invoked on this Result, as it contains results that include joined eager loads against collections
I would like to get the data the same way as for 1st level relationship, i.e.:
{D.abc : {ABC.a: {A}, ABC.b: {B}, ABC.c: {C}}}
Is it possible or do I have to change the select query completely and just create multiple joins and manually pick all the values I need?
I'm able to get correct records from the database when I just take the generated select statement and use it directly in a DB shell (MariaDB) so I assume that the only issue is my lack of understanding of how SQL handles/presents these records internally.
The issue was using uselist=True in one of the models, all relationships are working perfectly down to the lowest level now.
I am using EF6.1.2, database-first.
In one situation, this linq to sql query:
var data = from dl in ctx.ObjectContext.DocumentLines.Where(drow => drow.DocumentId == documentId)
join di in ctx.ObjectContext.DocumentsInfoes on dl.DocumentId equals di.Id
join ba in ctx.ObjectContext.Addresses on dl.DeliveryAddressId equals ba.Id into tba
from xba in tba.DefaultIfEmpty()
join sc in ctx.ObjectContext.SalesCategories on dl.SalesCategoryId equals sc.Id into tsc
from xsc in tsc.DefaultIfEmpty()
select new { Line = dl, DocumentInfo = di, DeliveryAddress = xba, SalesCategory = xsc };
var abc = data.ToList();
is not working.
The first documentline is correctly bound, but subsequent rows have some NULL or zero properties. If I run the generated SQL query, all columns are present and correct.
Is this a bug in Entity Framework? I have downloaded the EF source and I want to step into it to attempt to understand what's happening but don't know where to start looking.
The documentline table has a timestamp Version column for concurrency purposes. I have read a few similar issues where problems with a timestamp column, or other columns, (see Entity Framework does not pull through data from some columns) could cause subsequent columns to fail.
EDIT
On further investigation, it seems that, in the one call to this code that exhibits the problem, I can step over var abc = data.ToList(); without hitting any of the breakpoints in the setters of the properties of the DocumentLine entity, in the data model. Bizarre. All other calls to the code hit the breakpoints. Why isn't it loading the entities?
My DB have two tables - Question and Topic. To implement many-to-many relation, there is a mapping table which has following structure:
Table TopicQuestionMapping
int ID (Primary Key)
int QuestionID (Foreign key to Question table)
int TopicID (Foreign key to Topic table)
Now, in my EF I got something like
ViewData.Model = DB.QuestionMaster.Include("TopicQuestionMapping").First(x => x.ID == id);
and then I try to fetch topic like
Model.TopicQuestionMapping.First().TopicMaster.Name
(for simplification, I am just considering the first record)
The query populates the TopicQuestionMapping (I am getting count = 1). But the TopicMaster is null. Howe can I get it work?
It is something like Table A refer to Table B. Table B refer to Table C. I need to get data from Table C.
Include uses .'s to navigate the object graph.
So like .Include("TableA.TableB.TableC")
http://msdn.microsoft.com/en-us/library/bb896272.aspx
I am new to Entity Framework and LINQ and have run into a rather odd scenario.
I have been using the following query to return account information:
var account = ((from acct in _entities.Account
join m in _entities.Item on acct.Id equals m.Account.Id
where acct.Id == accountId && m.ItemNumber.EndsWith(itemNumber)
select acct) as ObjectQuery<Account>).Include("Item.ItemDetails");
We recently made some changes to the database and generated a new edmx file. Following the change the above query still returns the account and associated Item but the ItemDetails is no longer being included.
I have validated the SQL returned by the query and there doesn't seem to be anything wrong as the correct data is being returned.
Furthermore I don't see anthing different in the edmx file between the Item and ItemDetails objects as these were not changed and the navigation property is there.
Has anyone seen this before?
Thanks
In Include(...) is used the name of the navigation property so it will be good to check the exact name of the property from the .edmx (especially if it is singular or plural).
Also you can try to change the query like this:
var account = from acct in _entities.Account.Include("Item.ItemDetails")
join m in _entities.Item
on acct.Id equals m.Account.Id
where acct.Id == accountId && m.ItemNumber.EndsWith(itemNumber)
select acct;
You have one of two possible scenarios:
Item has a relationship to Account (expressed in your Entity Model as a EntityAssociation and in DB as a foreign key):
There is no relationship between Item set and Account set, hence, you must specify a join in LINQ as you have done.
Case 1: if this is the case, then you don't need a join statement... by selecting Acount.Item will naturally give you all items where Item.AccountID is equal to Account.ID
So your join statement: join m in _entities.Item on acct.Id equals m.Account.Id
has basically told Item to loop back onto Account to check the ID. If they were not already connected, then you could not have gotten m.Account.ID
Case 2: If there is no relationship between Account and Item, then the .Include() will definitely not work because the navigational property DOES NOT exist in your model.
Conclusion: Check your new model to see if a relationship exists between Account and Item. If yes, then remove the Join. If no relationship, then you've done something wrong.
Here is a select statement assuming scenario 1 and that Account.Item is not a collection:
var account = from acct in _entities.Account.Include("Item.ItemDetails")
where acct.Id == accountId && acct.Item.ItemNumber.EndsWith(itemNumber)
select acct;
HI I have a table with some some values (IDs), and of course when i get the result i got just the int IDs, but i want to put it more user friendly, for example when its the number 1, i want to put the string "Avaible", when its 2 "Not avaible", im on an N tiers enviroment and i need to get this done on the Model, whats the best way to accomplish this, i have to declare another class to project the strings, or must i use something like a dictionary, Key -> Value.
right now i just have this
return from t in db.products where t.productID==productID select t;
If you are using Linq to SQL you need another table to contain product status:
Table Name: Product Status
Fields: ProductStatusID int Indentity Primary Key
ProductStatus nvarchar(50)
Add a field to your Products Table:
Field to Add: ProductStatusID int
Add some statuses to your new table, and set the ProductStatusID of each product to an appropriate status id.
Add a constraint that connects the two ProductStatusID fields together. The easiest way do this is to create a diagram in SQL Server Management Studio Express, drag both tables onto the diagram, and then drag the ProductStatusID field from the ProductStatus table to the Products table, and click OK on the dialog that opens.
Rebuild your Linq to SQL data classes. You do this by deleting and recreating the DBML file, and dragging your tables into the designer again.
When you get a products object (p) from your dataContext object, you should now see this:
p.ProductStatus <-- The text description of the product's status.
Linq to SQL will reach into your ProductStatus table, and lookup the appropriate status description.