简体   繁体   中英

Entity Framework model and foreign key property

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.

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM