1

I have a straight forward scenario

class Person
{
    [Required]
    public int Age {get;set;}

    [Required]
    public virtual Pet Pet {get;set;}
}

class Pet
{
      ...
}

both Person & Pet are mapped in the context. lazy loading is enabled. If I attempt to update the age of the person I receive a validation error stating Pet is required.

var person = context.People.Find(id)
person.Age = 30;
context.SaveChanges(); //causes validation error.

I wouldn't think I need to load related entities for the context to produce the correct sql statements. Am I missing something, or is this just not possible?

solution given the limited options EF provides for this I went with disabling validation via an ActionFitler

public class DoNotValidateEntityFrameworkAttribute
    : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        actionContext
            .ControllerContext
            .Configuration
            .DependencyResolver
            .GetService<DbContext>()
            .Configuration
            .ValidateOnSaveEnabled = false;

        base.OnActionExecuting(actionContext);
    }
}

class MyController : ApiController
{
    [DoNotValidateEntityFramework]
    public void Put(int id, Model model)
    {
          ...
    }
}
4

1 に答える 1

0

1つのオプションは、代わりにこれを使用することです。

class Person
{
    [Required]
    public int Age {get;set;}

    [Required]
    public int PetId { get; set; }

    public virtual Pet Pet {get;set;}
}

これにより、FKのみが必要になりますが、エンティティは必要ありません。他のオプションは、不完全なオブジェクトグラフをサポートしていないため、検証をオフにすることです。

context.Configuration.ValidateOnSaveEnabled = false; 
于 2012-09-25T15:23:26.910 に答える