How to set up entity relationships in Entity Framework Core

Here we are on EF Core and got 3 tables:

  • news
  • Items
  • References

And also (except news, items): content, message, form, etc.

And my model definitions

public class Item { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public Link Link { get; set; } } public class News { public int Id { get; set; } public string Header { get; set; } public string Content { get; set; } public Link Link { get; set; } } public class Link { public int Id { get; set; } public string Type { get; set; } public int RowId { get; set; } public string Url { get; set; } } 

The Links table describes the URL for each news item and each item. This means that Links has 4 columns:

  • Id
  • Type - News or Product
  • RowId - contains the identifier of the product or news (depending on type)
  • URL

How to set up a relationship? Keep in mind that we need to enable Entity at the URL in the link table.

+8
c # asp.net-core .net-core entity-framework-core ef-code-first-mapping
source share
5 answers

Dapper. Just a Dapper that lets you write custom queries.

+1
source share

Update


I read your question again, and frankly, you do not need to create another table for links, just add a column to News and Item, etc., and everything will be fine.

 public class Item { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } public string Url { get; set; } } public class News { public int Id { get; set; } public string Header { get; set; } public string Content { get; set; } public string Url { get; set; } } 
0
source share

I would change Link to use a nullable int and allocate foreign keys for these tables:

 public class Link { public int Id { get; set; } public string Type { get; set; } public int? NewsId { get; set; } public int? ItemId { get; set; } public string Url { get; set; } } 
0
source share

I think you can remove the rowid from the link table and add the foreign key column to the other 2 tables referencing the id column in the link table.

Now that you have the URL, you have the type and ID, you can simply request the contents from the corresponding table.

0
source share

To have the NewRow property and restrictions for two other tables, you can use it like:

 public int RowId { public get { return this.Type.equals("news") ? NewsId.Value : ItemId.Value; }; private set { if(this.Type.equals("news")){ NewsId = value; } else{ ItemId = value; } } } 

And then set this property as not displayed in ContextDB.

0
source share

All Articles