开发者

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

开发者 https://www.devze.com 2023-02-22 07:58 出处:网络
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 descr

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 rel开发者_开发知识库ationship 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消