Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity framework code first class relationships

I am trying to create my model in Entity Framework and I am trying to go about it using code first option.

I currently have 3 tables in my database. My status table has all statuses used across the web application. I have a news table. And I have a news status table. The reason why I did it like this is because I don't want all the statuses available to the news items, just a couple of them. So my 3 tables will look like this:

News Table:

NewsId int required primary key
Title varchar required
Body varchar required
NewsStatusId int required foreign key

NewStatus Table:

NewsStatusId int required primary key
StatusId int required foreign key

Status Table

StatusId int required primary key
Name varchar required

When creating the classes for this, do I need to creates classes for News, Status and NewsStatus? I was thinking just for News and Status? What would my relationships look like between the 2/3 classes?

My News class looks like this

public class News
{
     public int NewsId { get; set; }
     // rest of my properties
     public int StatusId { get; set; }
}

Status class:

public class Status
{
     public int StatusId { get; set; }
     public string Name { get; set; }
}

What would these classes look like with relationships between the 2/3 classes?

Any code samples would be appreciated.

like image 624
Brendan Vogt Avatar asked Jan 27 '11 13:01

Brendan Vogt


Video Answer


2 Answers

You don't really need any fluent API for a basic Many-to-Many association between News and Status. Everything will be inferred by Code First base on conventions. That said, we can customize your DB schema with fluent API based on your requirements.

public class News
{
    public int NewsId { get; set; }
    public string Title { get; set; }

    public ICollection<Status> Statuses { get; set; }
}

public class Status
{
    public int StatusId { get; set; }
    public string Name { get; set; }

    public ICollection<News> Newses { get; set; }
}

public class Ctp5Context : DbContext
{
    public DbSet<News> Newses { get; set; }
    public DbSet<Status> Statuses { get; set; }
}

Please note that in a Many to Many association like this, there is not going to be a NewsStatusId as a foreign key on News class, instead, a NewsId foreign key will be show up on the link table that references the PK on News table. If you really need to have a NewsStatusId on News class, then we have to break this association to 2 one-to-many association which means we end up having 3 entities and not 2.

like image 52
Morteza Manavi Avatar answered Nov 11 '22 23:11

Morteza Manavi


Just News and Status. You'd write something like:

modelBuilder.Entity<News>()
    .HasMany(n => n.Statuses) 
    .WithMany(s => s.News);

(Adjust pluralizations to your liking.)

like image 30
Craig Stuntz Avatar answered Nov 11 '22 21:11

Craig Stuntz