0

I am trying insert into database my model with relation one to many:

I have two models:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }     

    public virtual Country Country { get; set; }
}

public class Country
{
    public int Id { get; set; }
    public string CountryName { get; set; }

    public virtual ICollection<User> Users { get; set; }
}

User user = new User()
{
     Name = model.Name,
     Surname = model.Surname,  
     Country = new Country { Id = 1 }
};

When I try to insert it to the database I get exception

Validation failed for one or more entities.

The CountryName field is required (CoutryName column is required in database)

I don't want each time call to database to get full Country object, any ideas?

2 Answers 2

3

Instead of instancing a new country, do something like this:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }     
    public int CountryId { get; set; }

    [ForeignKey("CountryId")]
    public virtual Country Country { get; set; }
}

public class Country
{
    public int Id { get; set; }
    public string CountryName { get; set; }

    public virtual ICollection<User> Users { get; set; }
}

User user = new User()
{
     Name = model.Name,
     Surname = model.Surname,  
     CountryId = 1;
};

This explicitly sets the CountryID on the User.

Sign up to request clarification or add additional context in comments.

2 Comments

I want to reduce these round trips to DB, and get the job done in one call.
Well you could set the Country ID explicitly. This assumes you know the CountryID at run time. This will work with a one to one or one to many, but not a many to many.
0

You should use "FK Associations" instead "Independent Associations" this is create article about it: http://blogs.msdn.com/b/efdesign/archive/2009/03/16/foreign-keys-in-the-entity-framework.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.