0

I have some questions with relationship of ef code first. My code:

public class user
{
    public user()
    {
    }

    public int id { get; set; }
    public string code { get; set; }
    public string name { get; set; }
}

public class dep
{
    public int id { get; set; }
    public Nullable<int> UserId { get; set; }
    public virtual user User { get; set; }
}

modelBuilder.Entity<dep>()
            .HasOptional(t => t.User)
            .WithOptionalDependent();

The table dep that code first auto generated has a foreign key named User_Id, but that is not what I want. I want to use the column UserId that I defined in the model. How will I change my code.

2 Answers 2

1

Think you can just add an attribute

[ForeignKey("UserId")]

on your User property.

Now, the question is why ? You're not in a Database, but in a ORM, an object world. You should work with User Navigation property, not with UserId. And if you need UserId, you should use User.Id.

But... that's your soultion ;)

1
  • when I added the foreignkey attribute,I got this exception: One or more validation errors were detected during model generation: \tSystem.Data.Entity.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'dep_User_Source' in relationship 'dep_User'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.
    – Raymond
    Jun 26, 2012 at 8:16
0

Could you try the following? I didn't test it, but think it should work:

    public class User
    {
        public int Id { get; set; }
        public string Code { get; set; }
        public string Name { get; set; }
        public Dep Dep { get; set; }
    }
    public class Dep
    {
        public int Id { get; set; }
        public User User { get; set; }
    }

    public class DepConfig : EntityTypeConfiguration<Dep>
    {
        public DepConfig()
        {
            this.HasRequired(t => t.User)
                    .WithOptional(t => t.Dep);
        }
    }

This assumes that Dep must have a User, but a User isn't required to have Dep. I added the property Dep to the User class so you can navigate in both directions.

Hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.