2016-11-04 143 views
-2

我有一个数据库优先的ASP.NET MVC应用程序和从数据库生成的实体模型,但我需要添加一些东西到未生成的模型。像这样以正确显示日期:实体框架模型和MVC模型不能映射

[DataType(DataType.Date)] 
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] 

所以我想创造另一种模式,在Models文件夹,并复制该EDMX了,并添加什么,我需要完全一样的东西。但是这会产生一个问题,我无法将对象从EntityModels.Movie转换为Models.Movie,我该如何实现这一目标?

我试过automapper,但并没有真正的工作,我读过的文档是针对旧版本(pre v5),它有一些过时的功能。 这里是我的实体模型代码:

namespace Movies.EntityModels 
{ 
    using System; 
    using System.Collections.Generic; 
    using System.ComponentModel.DataAnnotations; 

    public partial class Movie 
    { 
     public int ID { get; set; } 
     public string Title { get; set; } 
     public Nullable<System.DateTime> ReleaseDate { get; set; } 
     public Nullable<int> ID_Genre { get; set; } 
     public decimal Price { get; set; } 
     public string Rating { get; set; } 
     public int Quantity { get; set; } 

     public virtual Genre Genre { get; set; } 
    } 
} 

什么是达到我的目标,最好的办法?

+1

*我试过automapper,但并没有真正的工作* - 什么,所以你说的automapper不起作用?你可以在这里报告错误:https://github.com/AutoMapper/AutoMapper/issues –

+0

为什么不在你的部分类中添加你想要的字段/属性?在使用实体框架时这是相当普遍的做法。原因是生成的模型已经有一个部分修饰符。 –

回答

1

你可以手动编写一个映射器作为扩展方法,它非常简单。

public class Model() 
{ 
    public string Test1 {get;set;} 
    public string Test2 {get;set;} 
    public string Test3 {get;set;} 
} 

public class Entity(){ 
    public string Test1 {get;set;} 
    public string Test2 {get;set;} 
    public string Test3 {get;set;} 
} 

现在你创建一个扩展方法,例如“ToModel”,对实体对象转换为你的模型:

public static class MyExtensions{ 
    public static Model ToModel(this Entity entity){ 
     var model = new Model() 
     model.Test1 = entity.Test1; 
     model.Test2 = entity.Test2; 
     model.Test3 = entity.Test3; 

     return model; 
    } 
} 

和他们,只要你有你的实体对象,只需调用扩展方法:

public JsonResult test() 
{ 
    var entity = new Entity() 

    //{ Fill your entity properties from your dataset or something } 

    var model = entity.ToModel(); 
} 
+0

我应该在哪里放置扩展方法?任何课程或模型内? – Ribeiro

+0

任何一类。啊,我忘了添加,扩展方法应该是一个静态的 – Stormhashe

1

您是否尝试过使用[NotMapped]属性在相同的Movie模型(Movies.EntityModels中)中创建一个新的公共属性,可以说ReleaseDateFormatted。

+0

请重新写这个答案。目前感觉更像是评论。您可以将OP需要添加的更改作为代码片段添加进来,并将“您尝试过?”替换为“执行此操作”。提交 –