当我使用Mata Data Library项目时,如何为EF中的表准备ViewModel?

埃拉德

会员
已加入
2020年2月15日
留言内容
16
编程经验
1-3
您好
我有一个问题,我用一个EF从SQL服务器为我创建的单独的项目类中构建一个带有两个或多个表的项目类,并将引用添加到MVC项目中,以便Contrlloer知道如何关联表的对象-当用户输入值,然后放入框中特定视图中的文本,使用HttpPost-返回给Action的表单应在以类本身命名的模型模型中定义(该模型在单独的项目中由EF创建),并以方形设置方括号[MetadataType(该类的typeof)]。
我要捕获用户输入内容的操作要点将包含我定义MetadataType的特定表中实际上不存在的字段。尽管在下面的代码中您可以看到我在适合另一个表的特定字段上定义了数据注释。
我的问题是,当存在以下情况时,我如何知道如何以这种ViewModel模式构建
MetadataType?


C#:
//Library project
//With the classes EF created for
namespace MaterialLibrary.Models
{
    using System;
    using System.Collections.Generic;

    public partial class tbUser
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2994:DoNotCallOverridableMethodsInConstructors")]
        public tbUser()
        {
            this.tbVolunteerInfoes = new HashSet<tbVolunteerInfo>();
        }

        public int Id { get; set; }
        public string strFirstName { get; set; }
        public string strLastName { get; set; }
        public string strEmail { get; set; }
        public string strPassword { get; set; }
        public int Age { get; set; }
        public System.DateTime Date_Registration { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2707:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<tbVolunteerInfo> tbVolunteerInfoes { get; set; }
    }
}
//Table 2 which EF Carting
   public partial class tbVolunteerInfo
    {
        public int Id { get; set; }
        public bool Mode_Active { get; set; }
        public int HowDaysActivities { get; set; }
        public int Day { get; set; }
        public virtual tbUser tbUser { get; set; }
}
    }
}


//Now
//I will show the MataData model in MVC in-model

namespace VolMVC4.MaterialLibrary
{
    [MetadataType(typeof(tbVolunteerInfoMetaData))]
    public partial class tbVolunteerInfo
    {
    }
    public class tbVolunteerInfoMetaData
    {
   
        [Required(ErrorMessage = "required fname")]
        [Display(Name = "first name")]
        public string strFirstName { get; set; }

        [Required(ErrorMessage = "required lname")]
        [Display(Name = "Last Name")]
        public string strLastName { get; set; }
        [Required(ErrorMessage = "required city")]
        [Display(Name = "City")]
        public string strCity { get; set; }
        [Required(ErrorMessage = "required address")]
        [Display(Name = "Address")]
        //Such a field does not exist in the original table  tbVolunteerInfo but in another table
        public string strAddress { get; set; }
        [Required(ErrorMessage = "required phone")]
        [Display(Name = "Phone")]
        [DataType(DataType.PhoneNumber)]
        [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Invalid phone")]
        //Also the field it does not originally exist
        public string strPhone { get; set; }

        [Required(ErrorMessage = "required 电子邮件")]
        [RegularExpression("^[a-zA-Z0-9_\\.-][email protected]([a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$", ErrorMessage = "Invalid 电子邮件")]
        [Display(Name = "Email")]
        public string strEmail { get; set; }
        [Required]
        [StringLength(18, ErrorMessage = "password between {0}  and {2}", MinimumLength = 6)]
        //[RegularExpression(@"^((?=.*[a-z])(?=.*[A-Z])(?=.*\d)).+$")]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { set; get; }

        public System.DateTime DateRegistration { get; set; }

        [Required(ErrorMessage = "required Age)]
        [Display(Name = "Age")]
        [Range(19, 44, ErrorMessage = "Age must between 19 and 42")]
        public int Age { get; set; }
    

    }

}

//And Contrlloer

namespace VolMVC4.Controllers
{
    public class 首页Controller : Controller
    {
   
        public ActionResult SignUp()
        {
            string[] names;
            ViewBag.CountryList = new SelectList(new int[] { 1, 2, 3, 4, 5 });
            using (MaterialDbEntities MatDb = new MaterialDbEntities())
            {
                var qusCities = from s in MatDb.tbCities select s.strCity;
                names = qusCities.ToArray();
            }
            数组.Sort(names);
            ViewBag.CitiesList = new SelectList(names);
        }
        [HttpPost]
       //Here I want to get more fields that do not actually exist in the tbVolunteerInfo table
        public ActionResult SignUp(tbVolunteerInfo tb)
        {
        
            if (ModelState.IsValid)
            {
                using (MaterialDbEntities MatDb = new MaterialDbEntities())
                {

                        MatDb.tbVolunteers.Add(tb);
                        MatDb.SaveChanges();
              
                }
         
          }

            return View();
        }
    
    }
}
//And View SignUp
@model VolunteesMVC4.MaterialLibrary.tbVolunteerInfoMetaData

@{
    ViewBag.Title = "SignUp";
}

<h2>SignUp</h2>


@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>tbVolunteerInfoMetaData</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    

    <div class="form-group">
        @Html.LabelFor(model => model.strFirstName, htmlAttributes: new { @class = "control-label col-md" })
        <div class="col-md-15">
            @Html.EditorFor(model => model.strFirstName, new { htmlAttributes = new { @class = "form-control", placeholder = "First Name" } })
            @Html.ValidationMessageFor(model => model.strFirstName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.strLastName, htmlAttributes: new { @class = "control-label col-md" })
        <div class="col-md-15">
            @Html.EditorFor(model => model.strLastName, new { htmlAttributes = new { @class = "form-control", placeholder = "Last Name" } })
            @Html.ValidationMessageFor(model => model.strLastName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.strCity, htmlAttributes: new { @class = "control-label col-md" })
        <div class="col-md-15">
            @Html.DropDownListFor(m => m.strCity, (SelectList)ViewBag.CitiesList, "select city", new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.strCity, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.strAddress, htmlAttributes: new { @class = "control-label col-md" })
        <div class="col-md-15">
            @Html.EditorFor(model => model.strAddress, new { htmlAttributes = new { @class = "form-control", placeholder = "Address" } })
            @Html.ValidationMessageFor(model => model.strAddress, "", new { @class = "text-danger" })
        </div>
    </div>


    <div class="form-group">
        @Html.LabelFor(model => model.strPhone, htmlAttributes: new { @class = "control-label col-md" })
        <div class="col-md-15">
            @Html.EditorFor(model => model.strPhone, new { htmlAttributes = new { @class = "form-control", placeholder = "Phone" } })
            @Html.ValidationMessageFor(model => model.strPhone, "", new { @class = "text-danger" })
        </div>
    </div>



    <div class="form-group">
        @Html.LabelFor(model => model.strEmail, htmlAttributes: new { @class = "control-label col-md" })
        <div class="col-md-15">
            @Html.EditorFor(model => model.strEmail, new { htmlAttributes = new { @class = "form-control", placeholder = "Email" } })
            @Html.ValidationMessageFor(model => model.strEmail, "", new { @class = "text-danger" })
        </div>
    </div>



    <div class="form-group">
        @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md" })
        <div class="col-md-15">
            @Html.EditorFor(model => model.Password, new { htmlAttributes = new { @class = "form-control", placeholder = "Insert password" } })
            @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })
        </div>
    </div>



    <div class="form-group">
        @Html.LabelFor(model => model.HowDaysActivities, htmlAttributes: new { @class = "control-label col-md" })
        <div class="col-md-15">
            @Html.DropDownListFor(m => m.HowDaysActivities, (SelectList)ViewBag.CountryList, "Select in list", new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.HowDaysActivities, "", new { @class = "text-danger" })
        </div>
    </div>



    <div class="form-group">
        @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md" })
        <div class="col-md-15">
            @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control", placeholder = "Age" } })
            @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

<div>
    @Html.ActionLink("Back to 清单", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
 
Last edited:

跳伞

工作人员
已加入
2019年4月6日
留言内容
2,500
地点
弗吉尼亚州切萨皮克
编程经验
10+
就个人而言,由于它的怪癖和错误,我与Entity Framework的运行速度和距离要尽可能远。是的,EF 6和更高版本比EF 1.0和EF 2.0的可憎性要好得多,但是它仍然是一个奇怪的野兽。我认为您通过选择Database First EF(而不是Code First EF)使事情变得更加艰难。希望其他人可以加入该线程并提供一些帮助。祝好运!

要记住的是,视图模型的目的是为视图和控制器提供与实际数据模型进行对话的基础。回想一下Facade设计模式的主要目的是使事情变得更容易使用-它会照顾到隐藏在面向外部的界面后面的一些复杂性。因此,不仅可以使用EF生成的类,还可以创建自己的视图模型,该模型提供视图所需的接口以及视图和/或控制器所需的功能。
 

埃拉德

会员
已加入
2020年2月15日
留言内容
16
编程经验
1-3
我想我找到了解决方案,
这是一个简单的内置操作,通过Post返回,可以进行爬升
tbVolunteerInfoMetaData以及我保留了所有字段的数量。
所以这可能是一个愚蠢的问题,但问题是这实际上是否是正确的做事方式?
C#:
        [HttpPost]
       //Here I want to get more fields that do not actually exist in the tbVolunteerInfo table
        public ActionResult SignUp(tbVolunteerInfoMetaData tb)
        {
       
            if (ModelState.IsValid)
            {
                using (MaterialDbEntities MatDb = new MaterialDbEntities())
                {

                        MatDb.tbVolunteers.Add(tb);
                        MatDb.SaveChanges();
             
                }
       
          }

            return View();
        }
 
由主持人最后编辑:

埃拉德

会员
已加入
2020年2月15日
留言内容
16
编程经验
1-3
就个人而言,由于它的怪癖和错误,我与Entity Framework的运行速度和距离要尽可能远。是的,EF 6和更高版本比EF 1.0和EF 2.0的可憎性要好得多,但是它仍然是一个奇怪的野兽。我认为您通过选择Database First EF(而不是Code First EF)使事情变得更加艰难。希望其他人可以加入该线程并提供一些帮助。祝好运!

要记住的是,视图模型的目的是为视图和控制器提供与实际数据模型进行对话的基础。回想一下Facade设计模式的主要目的是使事情变得更容易使用-它会照顾到隐藏在面向外部的界面后面的一些复杂性。因此,不仅可以使用EF生成的类,还可以创建自己的视图模型,该模型提供视图所需的接口以及视图和/或控制器所需的功能。

我想我找到了解决方案's是一个简单的设置操作,该操作通过Post返回,它将获得tbVolunteerInfoMetaData爬升以及我保留了所有字段的多少。所以这可能是一个愚蠢的问题,但问题是这实际上是否是正确的做事方式?即使您自己说自己没有使用EF:
 [HttpPost]

       //Here I want to get more fields that do not actually exist in the tbVolunteerInfo table

        public ActionResult SignUp(tbVolunteerInfoMetaData tb)

        {

        

            if (ModelState.IsValid)

            {

                using (MaterialDbEntities MatDb = new MaterialDbEntities())

                {



                        MatDb.tbVolunteers.Add(tb);

                        MatDb.SaveChanges();

              

                }

        

          }



            return View();

        }
 

羊皮

退休程序员
工作人员
已加入
2018年9月5日
留言内容
1,926
地点
英国
编程经验
10+
请不要删除没有正当理由的帖子。

如果您对帖子的撰写方式有疑问,请对其进行编辑。
 
最佳 底部