Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF 4.1 Bidirectional one-to-one problem

Hi I am having a problem with a simple EF 4.1 code first model.

I have a class person and a class survey that are bidirectionally linked. The database model is correct but I always get this error:

Unable to determine the principal end of an association between the types 'DAL.Models.Survey' and 'DAL.Models.Person'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

Class Person

[Key]
        public Guid Id { get; set; }
        [Required]
        public string FirstName { get; set; }
        [Required]
        public string LastName { get; set; }
        [Required]
        public string Email { get; set; }

        public virtual Survey Survey { get; set; }

Class Survey

   [Key]
        public Guid Id { get; set; }

        public bool IsFinished { get; set; }

        public virtual Person Person { get; set; }

Datacontext:

 modelBuilder.Entity<Survey>().HasRequired(s => s.Person).WithOptional().WillCascadeOnDelete(true);

Can anyone help please

like image 635
Nealv Avatar asked Dec 14 '25 14:12

Nealv


1 Answers

You should define the other navigation property in your mapping since you have it in the model. Otherwise EF will create a second (one-to-many) association:

modelBuilder.Entity<Survey>()
            .HasRequired(s => s.Person)
            .WithOptional(p => p.Survey)
            .WillCascadeOnDelete(true);
like image 96
Slauma Avatar answered Dec 17 '25 10:12

Slauma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!