112

エンティティモデル

public partial class Categoies
{
    public Categoies()
    {
        this.Posts = new HashSet<Posts>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public Nullable<int> PositionId { get; set; }

    public virtual CategoryPositions CategoryPositions { get; set; }
    public virtual ICollection<Posts> Posts { get; set; }
}

モデルを表示

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

    [Required(ErrorMessage = "{0} alanı boş bırakılmamalıdır!")]
    [Display(Name = "Kategori Adı")]
    public string Name { get; set; }

    [Display(Name = "Kategori Açıklama")]
    public string Description { get; set; }

    [Display(Name = "Kategori Pozisyon")]
    [Required(ErrorMessage="{0} alanı boş bırakılmamalıdır!")]
    public int PositionId { get; set; }
}

CreateMap

Mapper.CreateMap<CategoriesViewModel, Categoies>()
            .ForMember(c => c.CategoryPositions, option => option.Ignore())
            .ForMember(c => c.Posts, option => option.Ignore());

地図

[HttpPost]
public ActionResult _EditCategory(CategoriesViewModel viewModel)
{
    using (NewsCMSEntities entity = new NewsCMSEntities())
    {
        if (ModelState.IsValid)
        {
            try
            {
                category = entity.Categoies.Find(viewModel.Id);
                AutoMapper.Mapper.Map<CategoriesViewModel, Categoies>(viewModel, category);
                //category = AutoMapper.Mapper.Map<CategoriesViewModel, Categoies>(viewModel);
                //AutoMapper.Mapper.Map(viewModel, category);
                entity.SaveChanges();

                // Veritabanı işlemleri başarılı ise yönlendirilecek sayfayı 
                // belirleyip ajax-post-success fonksiyonuna gönder.
                return Json(new { url = Url.Action("Index") });
            }
            catch (Exception ex)
            {

            }
        }

        // Veritabanı işlemleri başarısız ise modeli tekrar gönder.
        ViewBag.Positions = new SelectList(entity.CategoryPositions.ToList(), "Id", "Name");
        return PartialView(viewModel);
    }
}

エラー

タイプマップ設定が欠落しているか、マッピングがサポートされていません。マッピングタイプ:CategoriesViewModel-> Categoies_7314E98C41152985A4218174DDDF658046BC82AB0ED9E1F0440514D79052F84D NewsCMS.Areas.Admin.Models.CategoriesViewModel->System.Data.Entity.DynamicProxies.Categoies_7314E98C41152985A4218

宛先パス:Categoies_7314E98C41152985A4218174DDDF658046BC82AB0ED9E1F0440514D79052F84D

ソース値:NewsCMS.Areas.Admin.Models.CategoriesViewModel

私は何が欠けていますか?見つけようとしますが、問題がわかりません。

アップデート

Global.asaxのapplication_startで指定しました

protected void Application_Start()
{
    InitializeAutoMapper.Initialize();
}

InitializeClass

public static class InitializeAutoMapper
{
    public static void Initialize()
    {
        CreateModelsToViewModels();
        CreateViewModelsToModels();
    }

    private static void CreateModelsToViewModels()
    {
        Mapper.CreateMap<Categoies, CategoriesViewModel>();
    }

    private static void CreateViewModelsToModels()
    {
        Mapper.CreateMap<CategoriesViewModel, Categoies>()
            .ForMember(c => c.CategoryPositions, option => option.Ignore())
            .ForMember(c => c.Posts, option => option.Ignore());
    }
}
4

13 に答える 13

72

マッピングコード(CreateMap)はどこで指定しましたか?参照:AutoMapperはどこで構成しますか?

静的マッパーメソッドを使用している場合、構成はAppDomainごとに1回だけ行う必要があります。つまり、構成コードを配置するのに最適な場所は、ASP.NETアプリケーションのGlobal.asaxファイルなどのアプリケーションの起動です。

Mapメソッドを呼び出す前に構成が登録されていない場合は、Missing type map configuration or unsupported mapping.

于 2013-02-03T22:48:08.783 に答える
42

クラスAutoMapperプロファイルで、エンティティとビューモデルのマップを作成する必要があります。

ViewModel からドメイン モデルへのマッピング:

これは通常AutoMapper/DomainToViewModelMappingProfile

Configure()、次のような行を追加します

Mapper.CreateMap<YourEntityViewModel, YourEntity>();

ドメイン モデルから ViewModel へのマッピング:

ViewModelToDomainMappingProfile、次を追加します。

Mapper.CreateMap<YourEntity, YourEntityViewModel>();

要点の例

于 2014-11-13T11:54:18.113 に答える
22

Categoies_7314E98C41152985A4218174DDDF658046BC82AB0ED9E1F0440514D79052F84D例外のクラスに注意してください。それが Entity Framework プロキシです。EF コンテキストを破棄して、すべてのオブジェクトがデータベースから熱心に読み込まれ、そのようなプロキシが存在しないことを確認することをお勧めします。

[HttpPost]
public ActionResult _EditCategory(CategoriesViewModel viewModel)
{
    Categoies category = null;
    using (var ctx = new MyentityFrameworkContext())
    {
        category = ctx.Categoies.Find(viewModel.Id);
    }
    AutoMapper.Mapper.Map<CategoriesViewModel, Categoies>(viewModel, category);
    //category = AutoMapper.Mapper.Map<CategoriesViewModel, Categoies>(viewModel, category);
    entity.SaveChanges();
}

エンティティの取得がデータ アクセス レイヤー内で実行される場合 (もちろんこれが正しい方法です)、DAL からインスタンスを返す前に EF コンテキストを必ず破棄してください。

于 2013-02-03T23:10:36.557 に答える
9

エラーを削除するためにこれを行いました:

Mapper.CreateMap<FacebookUser, ProspectModel>();
prospect = Mapper.Map(prospectFromDb, prospect);
于 2013-07-22T22:16:46.390 に答える
6

Global.asax.cs ファイルを確認し、この行があることを確認してください

 AutoMapperConfig.Configure();
于 2015-10-20T13:14:25.910 に答える
6

解決策を見つけました。返信ありがとうございます。

category = (Categoies)AutoMapper.Mapper.Map(viewModel, category, typeof(CategoriesViewModel), typeof(Categoies));

しかし、私はすでにその理由を知りません。私は完全に理解できません。

于 2013-02-03T23:35:11.313 に答える
3

これは今のところかなり古い質問であることは知っていますが、アセンブリ属性を宣言していないことが適切な解決策であることがわかりました。

私のコードは次のとおりです。

using AutoMapper;
...

namespace [...].Controllers
{
    public class HousingTenureTypesController : LookupController<HousingTenureType, LookupTypeModel>
    {
        Mapper.CreateMap<HousingTenureType, LookupTypeModel>().ReverseMap();
    }
    ...
}

これは、名前空間宣言の前に次の行を追加することで修正されました。

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(HousingTenureTypesController), "AutoMapperStart")]

完全なコードは次のとおりです。

using AutoMapper;
...

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(HousingTenureTypesController), "AutoMapperStart")]

namespace [...].Controllers
{
    public class HousingTenureTypesController : LookupController<HousingTenureType, LookupTypeModel>
    {
        Mapper.CreateMap<HousingTenureType, LookupTypeModel>().ReverseMap();
    }
    ...
}
于 2015-06-12T00:16:48.283 に答える
0

Automapper をバージョン 6.2.2 にアップグレードします。それは私を助けました

于 2017-12-21T12:41:19.043 に答える