Open Closed

Id Field in Entity #40


0
antcandal created

I have the data model with some database tables with the key column not naming Id or ID. For example ClientId, being autoincrement identity. Have I to change all the key fields to Id or ID? with other names persisting throws error


5 Answer(s)
  • 0
    apexdodge created

    I think if you do ID instead of Id, then you're not following conventions and code-first won't know what to map unless you specify with a [ForeignKey("ClientID")] attribute, etc etc.

    But boilerplate takes care of Ids for you if your data model inherits from Entity

  • 0
    hikalkan created

    Hi,

    You can change mapped column name with two options:

    These are all EF stuff.

    Have a nice day.

  • 0
    a. h. created

    hikalkan: Hi,

    You can change mapped column name with two options:

    These are all EF stuff.

    Have a nice day.

    They are and they aren't.

    I have also had a bugger of a time with this.

    E.g Using ABP... I have had to do things to work around the issue of not having an "Id"

    public Client : Entity {
      [Key]
      public virtual int ClientID {get;set;} 
    }
    
    ...
    OnModelCreating(DBModelBuilder modelBuilder) {
      modelBuilder.Entity<Client>().Ignore(e => e.Id);
    }
    
    ...
    IClientRepository : DBRespositoryBase<Client>, IClientRepository {
    
      public virtual Client GetByID (int ClientID)
            {
                Client client = FirstOrDefault(agent => client .ClientID == ClientID);
    
                if (client == null)
                {
                    throw new Exception("Client not found: " + ClientID);
                }
                return Client;
            }
    }
    
    ClientDTO : EntityDTO {
      public ClientDTO (int ClientID) {
          Id = ClientID;
      }
    }
    
    etc...
    

    I can't use the IRepository's Get statement. Can't use AutoMapper... It is very much a ABP issue for me, unless I'm doing it wrong...

    Can you outline a quick to-do of what needs to be done to completely implement a table that doesn't use an Id in ABP? :D

  • 0
    hikalkan created

    Overriding Id works for me. Example:

    public class Person : Entity
        {
            [Column("PersonId")]
            public override int Id { get; set; }
    
            public virtual string Name { get; set; }
    
            [ForeignKey("PersonId")]
            public virtual ICollection<Phone> Phones { get; set; }
        }
    

    Here, I overrided Id and set Column attribute.

  • 0
    a. h. created

    Thank you.