简体   繁体   English

如何使用复合键在 model 的实体框架核心中获取单个实体?

[英]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.我对 C# 和 Entity Framework Core 完全陌生。 I have a model like:我有一个 model 像:

{
    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:这里的核心逻辑是我想防止一个CompanyProfile有多个BaseCategory的情况,因此我将这两个标记为复合键:

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?现在,问题是 - 有没有办法让另一个独特的价值像CompanyCategoryId来识别这个 model 的单个实体? I need it to get/update single entity on my frontend.我需要它来获取/更新我前端的单个实体。 Currently value of this field - CompanyCategoryId - is Guid but filled with zeros.该字段的当前值 - CompanyCategoryId - 是 Guid,但用零填充。 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.我想我可以在 DTO 中组合这两个复合键并将其作为字符串发送到前端,然后再次将其拆分为 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?"如果您的问题只是“我如何使CompanyCategoryId必须是唯一的?” 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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