Entity classes decoupled from LINQ to SQL provider for implementing the Repository pattern. How?

前端 未结 9 513
不知归路
不知归路 2021-02-02 02:57

I have looked over the Repository pattern and I recognized some ideas that I was using in the past which made me feel well.

However now I would like to write an applicat

相关标签:
9条回答
  • 2021-02-02 03:30

    The simplest way would be to decouple your entities from the datacontext: load the needed entity, decouple it from the DataContext, use it however you like, later use Attach() to couple it with a DataContext for saving.

    Sadly LINQ has no method to decouple entities from a datacontext, but you can just clone them, that works nicely. Simplest way would be something like this:

    public static T CloneEntity<T>(T source)
    {
      DataContractSerializer dcs = new DataContractSerializer(typeof(T));
      using (Stream stream = new MemoryStream())
      {
        dcs.WriteObject(stream, source);
        stream.Seek(0, SeekOrigin.Begin);
        return (T)dcs.ReadObject(stream);
      }
    }
    
    0 讨论(0)
  • 2021-02-02 03:36

    I did something similar with WCF

    1 On your DBML, set you Serialization mode to Unidirectional

    2 Set ALL columns on your tables to UpdateCheck=false

    3 Write your service something like the following:

       public class Service1 : IService1
        {
            public Company GetCompany(int companyId)
            {
                using (DataClasses1DataContext dc = new DataClasses1DataContext())
                {
                    return (from c in dc.Companies where c.CompanyId == companyId select c).Single();
                }
            }

        public void SaveCompany(Company company)
        {
            using (DataClasses1DataContext dc = new DataClasses1DataContext())
            {
                dc.Companies.Attach(company, true);
                dc.SubmitChanges();
            }
        }
    
        public void InsertCompany(Company company)
        {
            using (DataClasses1DataContext dc = new DataClasses1DataContext())
            {
                dc.Companies.InsertOnSubmit(company);
                dc.SubmitChanges();
            }
        }
    }
    

    4 Add a service reference

    0 讨论(0)
  • 2021-02-02 03:38

    I think you want POCO (Plain Old CLR Objects) support. LINQ to SQL has a adapter called Close2Poco.

    But I would advise making the switch to Entity Framework, at the moment they also have a POCO adapter, but in v2 its expected to be supported out of the box.

    0 讨论(0)
提交回复
热议问题