How to use interface properties with CodeFirst

后端 未结 7 2091
自闭症患者
自闭症患者 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 01:56

    A workaround is to create a special implementation for each interface you want to use with Entity Framework, utilizing the adapter pattern:

    Wrapper per Interface

    // Entity Framework will recognize this because it is a concrete type
    public class SecondLevelDomainRep: ISecondLevelDomain
    {
        private readonly ISecondLevelDomain _adaptee;
    
        // For persisting into database
        public SecondLevelDomainRep(ISecondLevelDomain adaptee)
        {
            _adaptee = adaptee;
        }
    
        // For retrieving data out of database
        public SecondLevelDomainRep()
        {
            // Mapping to desired implementation
            _adaptee = new SecondLevelDomain();
        }
    
        public ISecondLevelDomain Adaptee
        {
            get { return _adaptee; }
        }
    
        public string Id
        {
            get { return _adaptee.Id; }
            set { _adaptee.Id = value; }
        }
    
        // ... whatever other members the interface defines
    }
    

    Saving and Loading Example

        // Repositor is your DbContext
    
        public void SubmitDomain(ISecondLevelDomain secondLevelDomain)
        {
             Repositor.SecondLevelDomainReps.Add(new SecondLevelDomainRep(secondLevelDomain));
             Repositor.SaveChanges();
        }
    
        public IList RetrieveDomains()
        {
             return Repositor.SecondLevelDomainReps.Select(i => i.Adaptee).ToList();
        }
    

    Using Navigational Properties / Foreign Keys / Parent Child Mappings

    For more complex interfaces/classes, you may get InvalidOperationException - see Conflicting changes with code first foreign key in Entity Framework for an implementation that works with such object hierarchies

提交回复
热议问题