简体   繁体   中英

How to get single entity in Entity Framework Core of model with composite key?

I'm pretty new to C# and Entity Framework Core at all. I have a model like:

{
    public Guid CompanyCategoryId { get; set; }

    public Guid ParentCategoryId { get; set; }
    public virtual ParentCategory ParentCategory { get; set; }

    public Guid BaseCategoryId { get; set; }
    public virtual BaseCategory BaseCategory { get; set; }

    public Guid CompanyProfileId { get; set; }
    public virtual CompanyProfile CompanyProfile { get; set; }
}

The core logic here is I want to prevent situation where one CompanyProfile has more than one BaseCategory , thus I mark these two as composite key by:

builder.Entity<CompanyCategory>()
    .HasKey(c => new { c.CompanyProfileId, c.BaseCategoryId });

Now, the question is - is there any way to have another unique value like CompanyCategoryId to identify single entity of this model? I need it to get/update single entity on my frontend. Currently value of this field - CompanyCategoryId - is Guid but filled with zeros. I guess I can combine these two composite key in DTO and send it as a string to frontend and then again split it to separate keys in the controller. But I think it's rather ugly solutions... I will be really grateful for your help

If your question is simply "how do I make CompanyCategoryId required to be unique?" then you should just make and index on that column and mark it unique as per the documentation :

builder.Entity<CompanyCategory>()
    .HasIndex(b => b.CompanyCategoryId)
    .IsUnique();

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