How to use interface properties with CodeFirst

后端 未结 7 2065
自闭症患者
自闭症患者 2020-12-01 01:17

I have the following entities:

public interface IMyEntity
{
    [Key]
    int Id { get; set; }
    IMyDetail MyDetail { get; set; }
    ICollection

        
7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 02:07

    I've had the same problem and found a solution just like Nathan, but you can even take it one step further and have the properties named the same (here Extensions and IAddress.Extensions), by explicitly defining the interface:

    public interface IAddress
    {
        string Address { get; set; }
        IEnumerable Extensions { get; set; }
    }
    
    public interface IAddressExtension
    {
        string Key { get; set; }
        string Value { set; }
    }
    
    [Table("AddressExtensions")]
    public class AddressExtension : IAddressExtension
    {
        [Key]
        public string Id { get; set; }
        public string Key { get; set; }
        public string Value { get; set; }
    }
    
    [Table("Addresses")]
    public class Address : IAddress
    {
        [Key]
        public string Id { get; set; }
        public string Address { get; set; }
    
        public IEnumerable Extensions { get; set; }
    
        [NotMapped]
        IEnumerable IAddress.Extensions
        {
            get { return Extensions; }
            set { Extensions = value as IEnumerable; }
        }
    }
    

    Code First ignores the interface-property and uses the concrete class, while you can still access this class as an interface of IAddress.

提交回复
热议问题