0

我正在开发一个使用 Entity Framework 5 Code First、WebApi 和 ASPNET MVC 4 的项目。我有一个像这样的模型

public class Category
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }
}

而这个配置

public class CategoryMap : EntityTypeConfiguration<Categoria>
{
    public CategoryMap()
    {
        // Primary Key
        this.HasKey(t => t.Id);

        // Properties
        this.Property(t => t.Id)
            .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

        this.Property(t => t.Name)
            .HasMaxLength(50);

        this.Property(t => t.Description)
            .HasMaxLength(100);
    }
}

现在,在我的 webapi 控制器中(在 POST 方法中)我正在尝试验证发送的模型,但由于它是一个 POST(创建)并且 Id 是 IDENTITY,它即将为空或为空,因此 Model.Valid 说它无效。

public HttpResponseMessage Post(Category category)
{
    if (ModelState.IsValid)
    {
        ...
        return response;
    }

    throw new HttpResponseException(HttpStatusCode.BadRequest);
}

除了更改列的类型并且不检查模型是否有效之外,还有其他解决方案吗?

提前致谢!吉列尔莫。

4

2 回答 2

0

I haven't personally worked with the WebAPI, but is there some problem working with view models in the WebAPI instead of the actual domain object?

Create a "CreateCategory" view model class and bind that to the POST verb. This view model would be the same as your domain class less the fact it wouldn't expose an ID property and whatever other changes you'd like. Since there's no property to validate, there's nothing to trip up validation on.

public HttpResponseMessage Post(CreateCategoryViewModel category)

You validate the view model with Model.IsValid, it passes validation, then you map the view model to your actual model object.

Should work much the same as a standard MVC action binding a view model.

Hope that helps.

于 2012-11-28T04:09:24.463 回答
0

创建一个复制 Category 属性、Name 和 Description 的接口(比如 ICategory),并让 Category 类实现该接口。然后修改您的 HTTPRespoonseMessge Post 方法以采用 ICategory 类型的参数。

公共 HttpResponseMessage 帖子(ICategory 类别){ }

于 2012-12-03T16:49:11.353 回答