将类属性映射到表 .NET 中的通用列
我有一个 SQL Server 表,它具有 Text1、Text2.. 等通用名称。该表是这样设计的,因为不同的项目使用相同的结构。
我在 .NET 中有一个具有属性的类。 假设 Customer 类有一个名为 FirstName 的属性。
如何在应用程序中仅执行一次从 FirstName 到 Text1 的映射(中心位置),以便在创建不同的 DAL 方法时不必记住并硬编码整个应用程序中的映射?
例如,我希望应用程序知道我何时要更新、插入 FirstName,DAL 自动使用 Text1。 基本上我不必记住哪个属性属于哪个列。 这个想法是为了让开发人员不会以错误的方式映射属性/列。 它总是一致的。
注意:仅允许通过存储过程进行数据库插入、更新和删除。
I have have a SQL Server table which has generic names like Text1, Text2.. etc. The table was designed like this because the same structure is used for different projects.
I have a class in .NET which has properties. Say a Customer class has a property called FirstName.
How can I do the mapping from FirstName to Text1 just once (central place) in the application so that I don't have to remember and hard code the mappings all over the app when I create the different DAL methods?
For example, I want the app to know when I want to update, insert a FirstName, the DAL automatically uses Text1. Basically I don't have to remember which property goes to which column. The idea is so the developers do not map the properlies/columns in a wrong way. It's always consistent.
Note: Database inserts, updates and deletes are allowed through stored procedures only.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
研究一下那里的各种 ORM。 对于映射遗留数据库,NHibernate 是完美的。
Look into the various ORMs out there. For mapping a legacy database, NHibernate is perfect.
如果您无法使用 NHibernate(我强烈建议您这样做)或无法使用 LINQ to SQL(也许您的代码库是 .NET 2.0)那么...
您可能想要实现某种形式的工厂模式。 在工厂对象内部,您可能希望返回强数据集,然后使用对象到对象映射器在数据集和 DTO/View/Entity 对象之间进行转换。 来自 Los Techies 的 Jimmy 创建了一个很棒的开源对象到对象映射器,您可能会发现它非常有用:AutoMapper 。
快乐编码。
If you can't use NHibernate (and I would strongly suggest you do) or are not able to use LINQ to SQL (perhaps you're code base is .NET 2.0) then...
You will probably want to implement some form of factory pattern. Inside your factory object you might want to return a strongly data-set then use an object to object mapper to translate between your data-set and DTO/View/Entity objects. Jimmy from Los Techies has created a great open source object to object mapper which you might find very useful: AutoMapper.
Happy coding.