简体   繁体   English

使用复合主键生成控制器

[英]Generate Controller with composite primary key

I have many tables with a composite primary key in my database. 我的数据库中有很多带有复合主键的表。 When i generate a controller from my models, i always get methods that only have one parameter. 当我从模型中生成控制器时,我总是会得到只有一个参数的方法。 For example: 例如:

public ActionResult Edit(string id = null)
{
    ...
}

But what i want to achieve is to get the generated methods in my Controllers with all parameters for the primary key, something like this: 但是我想要实现的是在控制器中获取具有主键所有参数的生成方法,如下所示:

public ActionResult Edit(string pk1 = null, string pk2 = null, ...)
{
    ...
}

At the moment i have to change every single controller. 目前,我必须更改每个控制器。
Is it possible to generate this type of controller in some way? 是否可以通过某种方式生成这种类型的控制器?

The scaffolding template (T4) are located at [Visual Studio Directory]\\Common7\\IDE\\ItemTemplates\\CSharp\\Web\\[MVC Version]\\CodeTemplates\\AddController . 脚手架模板(T4)位于[Visual Studio Directory]\\Common7\\IDE\\ItemTemplates\\CSharp\\Web\\[MVC Version]\\CodeTemplates\\AddController You can modify or copy these templates and import them in your project and make the appropriate modifications or you can also create brand new ones. 您可以修改或复制这些模板,然后将其导入项目中并进行适当的修改,也可以创建全新的模板。 Here is valuable tutorial on how to achieve this 这是有关如何实现此目标的有价值的教程

Using Key attribute when you define your model 定义模型时使用Key属性

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace demomvc.Models
{
    public class MultipleKeyModel
    {
        [Key]
        public int Key1 { get; set; }
        [Key]
        public int Key2 { get; set; }
        [Key]
        public int Key3 { get; set; }
        public string Foo { get; set; }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM