0

I am having problem making a relationship between the two models. There are 3 composite keys in the tables. The problem occurs when I try to link the Category.Code to Service.CategoryCode. If I use the same column names in both tables, EF is able to handle. But I don't want to use Category.CategoryCode. I am new to EF. Please help me on how to achieve this by annotating and/or fluent api.

public class Category
{
    public Category()
    {
        this.Services= new HashSet<Service>();
    }
    [Key, Column(Order = 0)]
    public string ApplicationCode { get; set; }
    [Key, Column(Order = 1)]
    public string CompanyCode { get; set; }
    [Key, Column(Order = 2)]
    public string Code { get; set; }
    public string Description { get; set; }

    public virtual ICollection<Service> Services { get; set; }
}

public class Service
{
    [Key, Column(Order = 0)]
    [ForeignKey("Category")]
    public string ApplicationCode { get; set; }
    [Key, Column(Order = 1)]
    [ForeignKey("Category")]
    public string CompanyCode { get; set; }
    [Key, Column(Order = 2)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }
    [ForeignKey("Category")]
    public string CategoryCode { get; set; }
    public string Description { get; set; }
    public string Remarks { get; set; }

    public virtual Category Category { get; set; }
}
Picaleo
  • 1
  • 1
  • Possible duplicate of [Mapping a foreign key with a custom column name in Entity Framework 4.3 Code-First with Oracle](http://stackoverflow.com/questions/11148662/mapping-a-foreign-key-with-a-custom-column-name-in-entity-framework-4-3-code-fir) – Camilo Terevinto Jul 04 '16 at 16:17
  • Do you really need to include `ApplicationCode` and `CompanyCode` in `Service` PK? – Ivan Stoev Jul 04 '16 at 16:18

1 Answers1

0

Oh, I think it's too late to respond to your question. I'm using 'order' for many relationships. for example:

public class Subscript
{
    [Key, Column(Order = 0)]
    public long ID { get; set; }

    [ForeignKey("Customer")]
    public int CustomerId { get; set; }

    public string ChatType { get; set; }

    [ForeignKey("Channel")]
    public int? ChannelId { get; set; }
    public virtual Channel Channel { get; set; }

    [ForeignKey("Watermark") ,Column(Order = 1)]
    public int? Watermark_Id { get; set; }

    [ForeignKey("Watermark"), Column(Order = 2)]
    public string Watermark_Title { get; set; }

    public virtual Watermark Watermark { get; set; }

}

public class Watermark
{
    [Key, Column(Order = 0), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Key, Column(Order = 1, TypeName = "NVARCHAR")]
    [StringLength(100)]
    public string Title { get; set; }
}
MohammadSoori
  • 2,120
  • 1
  • 15
  • 17