Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a question about defining Foreign Key in EF Code First Fluent API. I have a scenario like this:

Two class Person and Car. In my scenario Car can have assign Person or not (one or zero relationship). Code:

    public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class Car
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Person Person { get; set; }
    public int? PPPPP { get; set; }
}

class TestContext : DbContext
{
    public DbSet<Person> Persons { get; set; }
    public DbSet<Car> Cars { get; set; }

    public TestContext(string connectionString) : base(connectionString)
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Car>().HasOptional(x => x.Person).WithMany().HasForeignKey(x => x.PPPPP).WillCascadeOnDelete(true);

        base.OnModelCreating(modelBuilder);
    }
}

In my sample I want to rename foreign key PersonId to PPPPP. In my mapping I say:

modelBuilder.Entity<Car>().HasOptional(x => x.Person).WithMany().HasForeignKey(x => x.PPPPP).WillCascadeOnDelete(true);

But my relationship is one to zero and I'm afraid I do mistake using WithMany method, but EF generate database with proper mappings, and everything works well.

Please say if I'm wrong in my Fluent API code or it's good way to do like now is done.

Thanks for help.

share|improve this question

1 Answer

up vote 1 down vote accepted

I do not see a problem with the use of fluent API here. If you do not want the collection navigational property(ie: Cars) on the Person class you can use the argument less WithMany method.

share|improve this answer
Ok, thanks for answer. – patryko88 Mar 25 '12 at 18:12
How can you have a "one to (one or zero)" relationship and use the WithMany() portion of the Fluent API? @patryko88 did you get your code to work as you wanted? If so, could you post the answer? Thanks! – Brian Behm Oct 16 '12 at 21:07
@BrianBehm EF allows you to have navigational properties on both sides of a one-to-one relationship only if you have shared PK mapping. By omitting the collection property, the relationship looks like one-to-one. – Eranga Oct 17 '12 at 4:33

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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