2016-09-06 6 views
0

私はAutomapperをMVCプロジェクトで使用します。私はASP.NET Identityも使用し、ApplicationUserクラスから私のカスタムユーザーテーブル(StudentとCoordinator)を継承します。問題はそれです;私はユーザーデータを取得し、そこにカスタムプロパティ(Numberと呼ばれます)が入っていますが、Automappeのマッピングを適用すると、ApplicationUserのプロパティだけが塗りつぶされ、Numberプロパティはnullになります。間違いや修正方法はありますか?Automapperはプロパティを埋め込むことができません

ドメインモデル:

public class ApplicationUser : IdentityUser<int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>, IUser<int> 
{ 
    public string Name { get; set; } 

    public string Surname { get; set; } 

    //code omitted for brevity 
} 

public class Student: ApplicationUser 
{  
    public int? Number { get; set; } 
} 

のViewModel:

public class RegisterViewModel 
{ 
    public int Id { get; set; }  

    public int? Number { get; set; } 

    //code omitted for brevity 
} 

コントローラー:

[AllowAnonymous] 
[HttpGet] 
public ActionResult Details(int? id) 
{ 
    if (id == null) 
    { 
     return new HttpStatusCodeResult(HttpStatusCode.BadRequest); 
    } 

    ApplicationUser user = db.Users.Find(id); 
    if (user == null) 
    { 
     return HttpNotFound(); 
    } 

    var config = new MapperConfiguration(cfg => { 
     cfg.CreateMap<ApplicationUser, RegisterViewModel>(); 
    }); 

    IMapper mapper = config.CreateMapper(); 
    //var source = new ApplicationUser(); 
    var dest = mapper.Map<ApplicationUser, RegisterViewModel>(user); 

    return PartialView("_Details", dest); 
} 
+0

もうひとつのマッピングを行う - あなたはすべての単一のコントローラのアクションにAutoMapperを設定しないでください。 AutoMapper設定は静的で、AppDomainごとに一度定義されたEF設定と同じです。 global.asaxなどでMapper.Initializeを使用し、マップを一度初期化する必要があります。 –

+0

@JimmyBogard返信ありがとうございます。 ** 1)**答えとして例を掲示していただけますか? ** 2)**私はApplicationUserをControllerのRegisterViewModelに変換する必要があります。その場合、これを解決する方法はありますか?返信していただけますか? –

+0

RegisterViewModelを表示できますか? – morecchia808

答えて

1

に役立ちます願っています。あなたは2つの異なるタイプについて話しています。 db.Users.Find(id);ApplicationUserの場合、ApplicationUserにはNumberというプロパティがないため、表示中のように機能しません。

db.Users.Find(id);から返されたオブジェクトが実際にはStudentである場合。その後castそれとStudent

Mapper.Initialize(cfg => 
{ 
    cfg.CreateMap<Student, RegisterViewModel>() 
     .ForMember(dest => dest.Id, opt => opt.Ignore()); 
}); 

Mapper.AssertConfigurationIsValid(); 

var myAppUser = new ApplicationUser(); 
var student = myAppUser as Student; 
var appUserResult = Mapper.Map<RegisterViewModel>(student); 
+1

問題を分析し、良い解決策を提案しました。同じ問題に遭遇した人** ForMember(dest => dest.Xxx、opt => opt.Ignore()** lineも他のすべてのカスタムプロパティに追加する必要があります。 –

0

いけないマップ「Appicat ionUser」そのようなマップの学生:

var dest = mapper.Map<Student, RegisterViewModel>(user); 

はまたのconfigureでマップを変更します。

cfg.CreateMap<Student, RegisterViewModel>(); 

はそれが私はそれがNumberをマッピングするために期待していない

+0

しかし、ユーザーはありがたいですが、ユーザーはAppicationUserタイプであり、ボクシングは問題を解決しません。 –

関連する問題