Вопрос

Could anybody tell me what's wrong with this code below, because I'm having problems getting an one-to-one relation working with EF 4.3 code first.

    // Problem with EF 4.3 code first, one-to-one relation

// context
// ------------
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{      
    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

    modelBuilder.Entity<SecondModel>().HasRequired(r => r.FirstModel).WithOptional(r => r.SecondModel).WillCascadeOnDelete(false);
}


// models
// --------

public abstract class MyBaseEntity : // some interfaces
{
    // ...

    [EdmScalarPropertyAttribute(EntityKeyProperty = true, IsNullable = false)]
    public virtual int Id
    {
        get { return GetPropertyValue<int>("Id"); }
        set { SetPropertyValue<int>("Id", value); }
    }

    // ...
}

public class FirstModel : MyBaseEntity
{
    // ...

    public int SecondModelID { get; set; }
    public virtual SecondModel SecondModel { get; set; }

    // ...
}

public class SecondModel : MyBaseEntity
{
    // ...

    public int FirstModelID
    {
        get { return GetPropertyValue<int>("FirstModelID"); }
        set { SetPropertyValue<int>("FirstModelID", value); }
    }
    public virtual FirstModel FirstModel { get; set; }

    // ...
}

// this code above doesn't seem to work :s
// when removing FirstModelID and removing SecondModelID i'm unable to create the the database

Have been trying all kinds of things, adding foreignkey attributes, (un)commenting some id's, following samples. Results were always: IDs in database are not correctly or it doesn't create the database.

Thanks in advance.

Это было полезно?

Решение

I dont have EF 4.3 but it is surprising if it is different from EF 4.1 in this regard. I've done it by configuring the model in the fluent API, overriding the ModelBuilder like this inside the DbContext class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
         modelBuilder.Entity<FirstModel>()
            .HasRequired(e => e.SecondModel)
            .WithRequiredPrincipal()
            .WillCascadeOnDelete(true);

            base.OnModelCreating(modelBuilder);

    }

And the classes:

public class FirstModel : MyBaseEntity
{
// ...

public virtual SecondModel SecondModel { get; set; }

// ...
}

public class SecondModel : MyBaseEntity
{
// ...

public int Id
{
    get { return GetPropertyValue<int>("FirstModelID"); }
    set { SetPropertyValue<int>("FirstModelID", value); }
}


// ...
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top