Timsen
Timsen

Reputation: 4126

EF code first make one to many relationship

I have 2 models, Task and Offer:

  public class Task
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int id { get; set; }
       [Key]
        public Guid TaskId { get; set; }
        public virtual ICollection<Offer> Offers { get; set; }

    }

    public class Offer
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int id { get; set; }
        [Key]
        public Guid OfferId { get; set; }
        public Guid TaskId { get; set; }
        [ForeignKey("TaskId")]
        public virtual Task Task { get; set; }


    }

A task can have many offers, and 1 offer have one tasks, i thought it shopuld be pretty straight forward, but i ran into different troubles, after googling for couple of hours i found out that i have to use fluent mapping, which i did:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Offer>().HasRequired(p => p.Task).WithMany(c => c.Offers).HasForeignKey(e=>e.TaskId2).WillCascadeOnDelete(false);
} 

but now i cant get rid of this error:

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Offers_dbo.Tasks_TaskId". The conflict occurred in database "test", table "dbo.Tasks", column 'TaskId'

What am i doing wrong?

Upvotes: 0

Views: 169

Answers (1)

Zafar
Zafar

Reputation: 3434

You do not necessarily need any settings through Fluent API.

You should be good by deleting the following code:

modelBuilder.Entity<Offer>().HasRequired(p => p.Task).WithMany(c => c.Offers).HasForeignKey(e=>e.TaskId2).WillCascadeOnDelete(false);

And changing your Task entity as follows:

public class Task{
    private ICollection<Offer> _offers;
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    public Guid TaskId { get; set; }
    public virtual ICollection<Offer> Offers {
        get { return _offers = _offers ?? new HashSet<Offer>(); }
        set { _offers = value; }
    }
}

And also, you need to delete public Guid TaskId { get; set; } and public int id { get; set; } from Offer entity. Any property that has id word on it will be treated as key for the table.

Upvotes: 4

Related Questions