简体   繁体   中英

How to setup entity relations in Entity Framework Core

Here we are on EF Core and got 3 tables:

  1. News
  2. Items
  3. Links

And more (except News, Items): Content, Post, 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; }
}

Table Links describe URL for every News and every Item. This means that Links has 4 columns:

  1. Id
  2. Type - news or item
  3. RowId - contains ID of Item or News (depends on the Type)
  4. URL

How to setup the relationships? Keep in mind that we need to resolve Entity by URL in Links table.

Dapper. Just Dapper that allows write custom queries.

Update


I read your question once more and well to be honest you don't have to create another table for Links, just add a Column to News and Item and so on.. and you 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; }
}

I'd change Link to use nullable int , and separate out the 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; }
}

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

Now, with you having the URL, you have the type and id, you can just query the content from respective table.

In order to have the property NewRow, and the constraints to the other two tables, you cold implement it like this:

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 mapped on the ContextDB.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM