views:

179

answers:

2

I have 2 tables that I import to EF model.
First table has a property [section] that acts as foreign key to the second table. When I map this property in model to the table and try to compile I get this error:

Problem in Mapping Fragments starting at lines 158, 174: Non-Primary-Key column(s) [Section] are being mapped in both fragments to different conceptual side properties - data inconsistency is possible because the corresponding conceptual side properties can be independently modified.

If i remove this property from the model it passes, but when I query the data I don't have the section field.

I know that I can get it by using the navigation field and reading this property from the second table, but to make it work I must include the other table in my query.

var res  = from name in Context.Table1.Include("Table2")...

Why do I need to include the association just for one field?

UPDATE
To make it more clear:

Table 1 has fields:
ItemId - key
section - foreign key
title

Table 2 has fields:
SectionId - key
Name

When I set the associations the section property from the first table must be removed.

A: 

In EF 4 you can use FK associations for this.

In EF 1 the easiest way to get one field from a related table is to project:

var q = from t1 in Context.Table1
        where //...
        select new 
        {
            T1 = t1,
            Section = t1.Section.SectionId
        };
var section = q.First().Section;

If it's a key property, you can get the value via the EntityKey:

var t1 = GetT1();
var section = (int)t1.SectionReference.EntityKey.Values[0].Value;

Generally, I don't like this last method. It's too EF-specific, and fails if your query MergeOption is set to NoTracking.

Craig Stuntz
what is this t1.Section? is it a foreign key property? if yes i don't have it.
verror
I'm guessing your field is called `Section` because that's what's in the error message. I might have guessed wrong. You don't show any of your schema, so it's hard to tell. Substitute the actual key property. I'll tweak the query to make this clearer.
Craig Stuntz
yes, its section but I don't have it thereBecause I needed to remove it when i imported the tables and created the association so when i press . , the intelisence doesn't have this property
verror
Is it possible to create partial class for the first table, there to create this Section property and fill it when query is executed?
verror
You mostly can't use non-entity properties (i.e., code you add in a partial class) in a LINQ query, because the EF doesn't know how to convert them to SQL.
Craig Stuntz
+1  A: 

What are your Primary Keys and is one Store Generated? I suspect you are missing a PK or an Identity somewhere.

Tip: One alternative when having mapping problems is to create the model you want in the EDMX designer and then ask it to create the database for you. Compare what it creates to what you have made in SQL and it's often easy to spot the mistakes.

Hightechrider