我使用的项目是SqlConnection
,SqlCommand
和普通SQL来访问存储库。现在,我正在尝试迁移到Linq2Sql,并且我想使用相同的模型。我怎样才能做到这一点?如何使Linq2Sql与我的模型一起工作
我将减少项目结构为最小的有意义的例子。
比方说,我有以下类:
namespace Model
{
public class User
{
public int Id { get; set; }
}
}
在Model
命名空间中所有型号的一个功能于一身的数据库实体的副本。
namespace Repository
{
public class UserRepository
{
private _sqlConnectionHelper = new SqlConnectionHelper();
public User GetUser()
{
var reader = _sqlConnectionHelper
.ExecuteAndReturnReader("SELECT * FROM [dbo].[Users]");
while (reader.Read())
{
return new User
{
Id = (int)reader["Id"]
};
}
return null;
}
}
}
现在我正在尝试迁移到Linq2Sql。我在Repository
项目中创建了MyContext.dmbl
文件,User
表。它已经产生了以下类:
namespace Repository
{
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.Users")]
[global::System.Runtime.Serialization.DataContractAttribute()]
public partial class User: INotifyPropertyChanging, INotifyPropertyChanged
{
private int _ID;
public int ID
{
get
{
return this._ID;
}
set
{
if ((this._ID != value))
{
this.OnIDChanging(value);
this.SendPropertyChanging();
this._ID = value;
this.SendPropertyChanged("ID");
this.OnIDChanged();
}
}
}
// Some other methods
}
}
现在的问题是,我有很多的实体,仓库,模型等。我不想改变整个项目中使用新生成的模型,但不我的名字空间是Model
。我如何使Linq2Sql
与我的模型一起使用?
它也影响我的架构,因为在这些模型的情况下,实体和存储库是同一个对象。我不需要我的实体是CRUD对象。我只想做最小的改动项目和只使用LINQ方便的请求,而不是普通的SQL是这样的:
namespace Repository
{
public class UserRepository
{
private MyContextDataContext _myContext = new MyContextDataContext();
public User GetUser()
{
return _myContext.Users.FirstOrDefault();
}
}
}
或者我只是不明白一些事情的Linq2Sql
目的和逻辑,这是它如何工作只喜欢?
当然,我可以编写转换器或使用反射并按属性制作对象属性的副本,但听起来不是一个好的解决方案。