Dapper的参数化更新和插入?

时间:2016-06-23 19:10:37

标签: c# sql dapper

我正在使用Dapper作为我的Windows C#表单应用程序。我注意到他们的大多数CRUD操作都以类名作为参数。 例如,如下两个表:

    "Employee" Table
        Column Name  | Data Type |
        -------------------------
        EmpName      | string    |
        EmpNo        | string    |
        --------------------------

Employee.cs
[Table("Employee")]
public class Employee
{
   [Key]
   public string EmpNo {get;set;}
   public string EmpName {get;set;}
}

    "User" Table
        Column Name   | Data Type |
        -------------------------
        UserName      | string    |
        UserNo        | string    |
        --------------------------
User.cs
[Table("User")]
public class User
{
   [Key]
   public string UserNo {get;set;}
   public string UserName {get;set;}
}


    eg. var users= connection.Query<User>("select * from User" );
        var employees = connnection.GetList<Employee>();

将完成相应的任务。 但是,据我所知,connection.Insert<User>(user); or connection.Update<Employee>(emp);不存在。 如果我错了,请纠正我,是否有任何工作要让更新和插入让小巧的人知道班级类型? 我很清楚Query()Execute(),事实上我现在正在使用它们。有没有可能让它像GetList(ClassName);一样简单?

2 个答案:

答案 0 :(得分:3)

Dapper处理的事情与你要求的有点不同。没有Insert或Update方法。相反,你会想要这样做插入:

var bodyParser = require('body-parser');
var Settings = require('../models/settings');
var Source = require('../models/source');

module.exports = function (app, express) {
    var apiRouter = express.Router();    

    apiRouter.route('/settings')
        .get(function (req, res) {
            //check to see if any records exists
            var settingsPromise = Settings.find({}).exec();
            settingsPromise.then(function (settings) {
                if (settings.length == 0) {
                    var defaultSettings = new Settings();
                    var newPromise = defaultSettings.save(); // might need more error handling here
                    newPromise.then(function () { res.json(defaultSettings) })
                }
                else {
                    res.json(settings[0]);
                }
            })
                .catch(function (err) {
                    res.json({ success: false, message: err })
                })
        })
        .put(function (req, res) {
            var id = req.body.id;
            var promise = Settings.findOneAndUpdate({ _id: id }, req.body).exec();
            promise.then(function (settings) {
                res.json({ status: true, message: 'Settings updated.' });
            })
                .catch(function (err) {
                    res.json({ success: false, message: err });
                });
        });

    apiRouter.route('/sources')
        .get(function (req, res) {
            // show all sources
            var sourcePromise = Source.find({});
            sourcePromise.then(function (source) {
                if (source.length == 0) {
                    // add default sources
                    var addActions = defaultSources.map(defaultPromises) // a handy collection of promises
                    var results = Promise.all(addActions); // wait for them all to complete here with 'Promise.all'
                    results.then(function (data) {
                        res.json(data);
                    })
                    results.catch(function (err) {
                        res.json({ success: false, message: err });
                    })
                }
                else {
                    res.json(source);
                }
            })
                .catch(function (err) {
                    res.json({ success: false, message: err });
                })
        })
        .post(function (req, res) {
            var newSource = new Source();
            var sourcePromise = newSource.save();
            sourcePromise.then(function(source){
                res.json({success: true, message : 'New source added.'})
            })
            .catch(function(err){
                res.json({ success: false, message: err });
            })

        })
    apiRouter.route('/sources/:source_id')
        .get(function (req, res) {
            // show single source
            var sourcePromise = Source.findOne(req.params.source_id).exec();
            sourcePromise.then(function (source) {
                return res.json(source);
            })
                .catch(function (err) {
                    return res.json({ status: false, message: err })
                })
        })
        .put(function (req, res) {
            // show single source
            var sourcePromise = Source.findOneAndUpdate({ _id: req.params.source_id }, req.body).exec();
            sourcePromise.then(function (source) {
                return res.json({ status: true, message: 'Source updated.' });
            })
                .catch(function (err) {
                    return res.json({ status: false, message: err })
                })
        })
        .delete(function(req, res){
            var sourcePromise = Source.findOneAndRemove({_id: req.params.source_id}).exec()
            sourcePromise.then(function(source){
                return res.json({ status: true, message: 'Source deleted.' });
            })
                .catch(function (err) {
                    return res.json({ status: false, message: err })
                })
        })

    return apiRouter;

};

var defaultPromises = function (item) {
    s = new Source();
    s.domain = item.domain;
    s.loginPage = item.loginPage;
    s.scanUrl = item.scanUrl;
    s.sourceType = item.sourceType;
    s.cssSelect = item.cssSelect;
    return savePromise = s.save();
}

var defaultSources = [
    {
        domain: 'http://tehparadox.com',
        loginPage: 'http://tehparadox.com',
        scanUrl: 'http://tehparadox.com/forum/f63/tv-shows-2010-2011-hd-1439182/',
        sourceType: 'TV and Movies',
        cssSelect: '.post a'
    },
    {
        domain: 'http://tehparadox.com',
        loginPage: 'http://tehparadox.com',
        scanUrl: 'http://tehparadox.com/forum/f63/tv-shows-2010-2011-hd-1439182/',
        sourceType: 'TV and Movies',
        cssSelect: '.post a'
    },
    {
        domain: 'http://tehparadox.com',
        loginPage: 'http://tehparadox.com',
        scanUrl: 'http://tehparadox.com/forum/f63/tv-shows-2010-2011-hd-1439182/',
        sourceType: 'Index',
        cssSelect: '.post a'
    },
    {
        domain: 'http://tehparadox.com',
        loginPage: 'http://tehparadox.com',
        scanUrl: 'http://tehparadox.com/forum/f63/tv-shows-2010-2011-hd-1439182/',
        sourceType: 'Search',
        cssSelect: '.post a'
    }
]

这是直接来自Sam Saffron,https://samsaffron.com/archive/2012/01/16/that-annoying-insert-problem-getting-data-into-the-db-using-dapper

对于更新,您需要这样的代码:

var p = new Product { Name = "Sam", Description = "Developer" };
p.Id = cnn.Query<int>(@"insert Products(Name,Description) 
values (@Name,@Description) 
select cast(scope_identity() as int)", p).First();

答案 1 :(得分:2)

感谢Marc Gravell。我发现它here。 Dapper的开源开发确实实现了Insert<ClassName>(obj)Update<ClassName>(obj)