C
C#10mo ago
engineertdog

FK on Guid

I have the following two classes
c#
public class PiCollectiveIdentity {
public Guid Id { get; set; } = new Guid();
public long IdentityId { get; set; }
public required string Name { get; set; }
[ForeignKey("IdentityName")]
public IList<PiCollectiveIdentityMapping> Mappings { get; set; } = new List<PiCollectiveIdentityMapping>();
}

public class PiCollectiveIdentityMapping{
public Guid Id { get; set; } = new Guid();
public DateTime CollectionDate { get; set; } = DateTime.UtcNow;
public required string IdentityName { get; set; }
public PiCollectiveIdentity ? Identity { get; set; } = null;
}
c#
public class PiCollectiveIdentity {
public Guid Id { get; set; } = new Guid();
public long IdentityId { get; set; }
public required string Name { get; set; }
[ForeignKey("IdentityName")]
public IList<PiCollectiveIdentityMapping> Mappings { get; set; } = new List<PiCollectiveIdentityMapping>();
}

public class PiCollectiveIdentityMapping{
public Guid Id { get; set; } = new Guid();
public DateTime CollectionDate { get; set; } = DateTime.UtcNow;
public required string IdentityName { get; set; }
public PiCollectiveIdentity ? Identity { get; set; } = null;
}
Where each database record will have it's own unique ID, but the relationship between the two records is based on name (due to pulling the data from a 3rd party system). However, this throws an error when attempting to migrate for 'PiCollectiveIdentityMapping.Mappings' with foreign key properties {'IdentityName' : string} cannot target the primary key {'Id' : Guid} because it is not compatible What is the proper way to build the relationship?
5 Replies
Angius
Angius10mo ago
You set the FK on the "one" side of "one to many" And, I believe, you will need to configure the name to be a key
engineertdog
engineertdogOP10mo ago
I moved it from attribute based to the onModelCreating. I like to keep them in the models but sometimes they're just dumb
Jimmacle
Jimmacle10mo ago
another option is to use IEntityTypeConfiguration classes, then you can keep entity configuration out of the dbcontext and still use the fluent API
Jimmacle
Jimmacle10mo ago
Creating and Configuring a Model - EF Core
Overview of creating and configuring a Entity Framework Core model via Fluent API, Data Annotations and conventions.
engineertdog
engineertdogOP10mo ago
Oh right, I forgot about that method. That's certainly an option and if I end up with more scenarios where the attribute route doesn't cover the needs, I'll look to bring that back in
Want results from more Discord servers?
Add your server