简体   繁体   中英

How to use Entity Framework 4.1 Code First to force a one to one relationship for a one to many relationship in the database

I am trying to change EF1 for EF4.1 code first in an application where the schema cannot be changed because it is used in SQL Server Replication. The schema is dreadfully poor and in many places describes relationships completely back to front.

What I am trying to do is create a one to one relationship between two classes, but the database schema erroneously maintains the data as a one to many.

public class ClassA
{
    public ClassB
    {
        get;
        set;
    }
}

Unfortunately the table ClassB in the database has reference to ClassAId rather than ClassA having a ClassBId as shown here:

CREATE TABLE [dbo].[ClassA]
    [Id] [bigint] IDENTITY


CREATE TABLE [dbo].[ClassB]
    [Id] [bigint] IDENTITY
    [ClassAId] [bigint]

How to I set up my mapping file that inherits from EntityTypeConfiguration to force this relationship.

public class ClassAMapping : EntityTypeConfiguration<ClassA>
{
    public ClassA()
    {
        HasKey(f => f.Id);

        // what happens here to force a one to one????
    }
}

Thanks to Jakub Konecki for the link to the article, it did not actually contain the answer I was looking for, but it did link to an earlier post in the series where I found the answer.

The way to force this one to one association is as follows:

public class ClassAMapping : EntityTypeConfiguration<ClassA>
{
    public ClassA()
    {
        HasKey(x => x.Id);

        HasOptional<ClassB>(x => x.ClassB)
                .WithRequired()
                .Map(x => x.MapKey("ClassBId"));
    }
}

This mapping reads as:

"The ClassA entity has an optional association with one ClassB entity, but this association is required for the ClassB entity."

Please note that this solution is uni-directional and will not allow the following:

ClassB b = new ClassB();
string test = b.ClassA.SomeString;

If a bi-directional association is required check out the link that was found which elaborates further.

The article linked by Jakub is part of a series of posts which are a good read if you are trying to sort out your EF4.1 associations.

Take a look here:

http://weblogs.asp.net/manavi/archive/2011/01/23/associations-in-ef-code-first-ctp5-part-3-one-to-one-foreign-key-associations.aspx

It's an article for CTP5, but I think you will be able to 'translate' fluent API calls to RTm version.

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