4

Let's say I have these models:

public class Component
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Type { get; set; }
    public List<ComponentUpdate> Updates { get; set; }
    public ComponentUpdate LastUpdate { get; set; }
}

public class ComponentUpdate
{
    public int Id { get; set; }
    public DateTime Timestamp { get; set; }
    public Component Component { get; set; }
    public string Message { get; set; }
}

The reason I'm saving the LastUpdate field instead of manually pulling it according to the highest 'TimeStamp' is because of speed. It would be faster to store a reference instead of checking the entire list every request.

When I'm trying to migrate the DB it throws an error saying I cannot have my properties participate in more than a single relationship. I'm mapping the relationships in my context class and I don't think I'm doing it right since I have ComponentUpdate.Component mapped twice.

I've looked on several solutions but some were outdated and some just did not fit this scenario.

Thanks for helping.

Edit

Mapping accordingly:

modelBuilder.Entity<Component>().HasMany(c => c.Updates).WithOne(u => u.Component);
modelBuilder.Entity<ComponentUpdate>().HasOne(u => u.Component).WithOne(c => c.LastUpdate);
J. Doe
  • 81
  • 1
  • 6
  • Have you seen [this question](https://stackoverflow.com/questions/38520695/multiple-relationships-to-the-same-table-in-ef7core)? It may help you. It looks what you want should work fine. Maybe you just need to explicitly configure the relationships in your context (I'm not sure). – Alisson Reinaldo Silva Jan 30 '18 at 11:37
  • Can you share the code for your mappings? – SpruceMoose Jan 30 '18 at 11:39
  • @Alisson I did, without any success. – J. Doe Jan 30 '18 at 11:55
  • @CalC Yes, adding – J. Doe Jan 30 '18 at 11:56
  • For what I understand, I think you shouldn't map the `LastUpdate` field to the database (using `[NotMapped]` for example) – Omar Muscatello Jan 30 '18 at 11:57
  • @OmarMuscatello but what if my system restarts? I would want the last one to be available – J. Doe Jan 30 '18 at 12:00
  • 1
    "It would be faster to store a reference instead of checking the entire list every request." What are you basing that on? Either way, it's a single query. And neither query would be anything to SQL Server. *Don't prematurely optimize.* Let something *actually* be a problem, before you attempt to fix it. As it stands, you've painted yourself into a corner trying to "optimize" something that doesn't need to be optimized, and your code is actually more stable and more easily understood *without* it. – Chris Pratt Jan 30 '18 at 14:30

0 Answers0