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

前端 未结 9 533
不知归路
不知归路 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 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);
      }
    }
    

提交回复
热议问题