Required Associated Entity Causing Validation ErrorsEntity Framework vs LINQ to SQLValidation failed for one or more entities while saving changes to SQL Server Database using Entity FrameworkThe relationship could not be changed because one or more of the foreign-key properties is non-nullableFastest Way of Inserting in Entity FrameworkNHibernate - Set foreign key column to null when deletingValidation failed for one or more entities. See 'EntityValidationErrors' property for more detailsDbEntityValidationException - How can I easily tell what caused the error?Add data annotations to a class generated by entity frameworkSolving “The ObjectContext instance has been disposed and can no longer be used for operations that require a connection” InvalidOperationExceptionEntity Framework Core Put Operation Not Working

Why did the Soviet Union not "grant" Inner Mongolia to Mongolia after World War Two?

Comma Code - Automate the Boring Stuff with Python

What secular civic space would pioneers build for small frontier towns?

Safe to use 220V electric clothes dryer when building has been bridged down to 110V?

Which place in our solar system is the most fit for terraforming?

Subverting the emotional woman and stoic man trope

List of 1000 most common words across all languages

What is the meaning of word 'crack' in chapter 33 of A Game of Thrones?

What are the consequences of high orphan block rate?

How do you use the interjection for snorting?

Co-supervisor comes to the office to help her students, which distracts me

Worms crawling under skin

OSM Thunderforest API keys in QGIS3

How do pilots align the HUD with their eyeballs?

Averting Bathos

What is the difference between an astronaut in the ISS and a freediver in perfect neutral buoyancy?

Tesla coil and Tesla tower

A food item only made possible by time-freezing storage?

I am 15 years old and do not go to a Yeshiva but would like to learn Talmud. A few rabbis near me said they could teach me. How should I start

Why weren't the Death Star plans transmitted electronically?

Reorder a matrix, twice

Why does C++ have 'Undefined Behaviour' and other languages like C# or Java don't?

Is it acceptable to say that a reviewer's concern is not going to be addressed because then the paper would be too long?

Aesthetic proofs that involve Field Theory / Galois Theory



Required Associated Entity Causing Validation Errors


Entity Framework vs LINQ to SQLValidation failed for one or more entities while saving changes to SQL Server Database using Entity FrameworkThe relationship could not be changed because one or more of the foreign-key properties is non-nullableFastest Way of Inserting in Entity FrameworkNHibernate - Set foreign key column to null when deletingValidation failed for one or more entities. See 'EntityValidationErrors' property for more detailsDbEntityValidationException - How can I easily tell what caused the error?Add data annotations to a class generated by entity frameworkSolving “The ObjectContext instance has been disposed and can no longer be used for operations that require a connection” InvalidOperationExceptionEntity Framework Core Put Operation Not Working






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















I have something like the following:



public class EntityA

[Required]
long? EntityBId get; set;

[ForeignKey("EntityBId ")]
public virtual EntityB get; set;


public class EntityB

[Key]
long EntityBId get; set;



When I go to use it as follows I get a validation error because required property EntityBId is null.



EntityA a = new EntityA();
a.EntityB = new EntityB();
dbContext.EntityAs.Add(EntityA);
dbContext.SaveChanges();


However if I remove the [Required] attribute then both EntityA and EntityB get added to the database and EntityBId gets populated by the SaveChanges call.



How can I mark EntityBId as [Required] and avoid entity framework validation from failing?










share|improve this question


























  • Why do you need to mark it as [Required] if you don't need it to be required?

    – Alexander
    Mar 28 at 23:37











  • @Alexander it is required

    – denver
    Mar 29 at 14:24

















0















I have something like the following:



public class EntityA

[Required]
long? EntityBId get; set;

[ForeignKey("EntityBId ")]
public virtual EntityB get; set;


public class EntityB

[Key]
long EntityBId get; set;



When I go to use it as follows I get a validation error because required property EntityBId is null.



EntityA a = new EntityA();
a.EntityB = new EntityB();
dbContext.EntityAs.Add(EntityA);
dbContext.SaveChanges();


However if I remove the [Required] attribute then both EntityA and EntityB get added to the database and EntityBId gets populated by the SaveChanges call.



How can I mark EntityBId as [Required] and avoid entity framework validation from failing?










share|improve this question


























  • Why do you need to mark it as [Required] if you don't need it to be required?

    – Alexander
    Mar 28 at 23:37











  • @Alexander it is required

    – denver
    Mar 29 at 14:24













0












0








0








I have something like the following:



public class EntityA

[Required]
long? EntityBId get; set;

[ForeignKey("EntityBId ")]
public virtual EntityB get; set;


public class EntityB

[Key]
long EntityBId get; set;



When I go to use it as follows I get a validation error because required property EntityBId is null.



EntityA a = new EntityA();
a.EntityB = new EntityB();
dbContext.EntityAs.Add(EntityA);
dbContext.SaveChanges();


However if I remove the [Required] attribute then both EntityA and EntityB get added to the database and EntityBId gets populated by the SaveChanges call.



How can I mark EntityBId as [Required] and avoid entity framework validation from failing?










share|improve this question
















I have something like the following:



public class EntityA

[Required]
long? EntityBId get; set;

[ForeignKey("EntityBId ")]
public virtual EntityB get; set;


public class EntityB

[Key]
long EntityBId get; set;



When I go to use it as follows I get a validation error because required property EntityBId is null.



EntityA a = new EntityA();
a.EntityB = new EntityB();
dbContext.EntityAs.Add(EntityA);
dbContext.SaveChanges();


However if I remove the [Required] attribute then both EntityA and EntityB get added to the database and EntityBId gets populated by the SaveChanges call.



How can I mark EntityBId as [Required] and avoid entity framework validation from failing?







c# entity-framework






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 29 at 0:55









TanvirArjel

12.7k4 gold badges22 silver badges56 bronze badges




12.7k4 gold badges22 silver badges56 bronze badges










asked Mar 28 at 17:38









denverdenver

1,80517 silver badges32 bronze badges




1,80517 silver badges32 bronze badges















  • Why do you need to mark it as [Required] if you don't need it to be required?

    – Alexander
    Mar 28 at 23:37











  • @Alexander it is required

    – denver
    Mar 29 at 14:24

















  • Why do you need to mark it as [Required] if you don't need it to be required?

    – Alexander
    Mar 28 at 23:37











  • @Alexander it is required

    – denver
    Mar 29 at 14:24
















Why do you need to mark it as [Required] if you don't need it to be required?

– Alexander
Mar 28 at 23:37





Why do you need to mark it as [Required] if you don't need it to be required?

– Alexander
Mar 28 at 23:37













@Alexander it is required

– denver
Mar 29 at 14:24





@Alexander it is required

– denver
Mar 29 at 14:24












2 Answers
2






active

oldest

votes


















0
















See this link for usage of Required annotation: https://docs.microsoft.com/en-us/ef/ef6/modeling/code-first/data-annotations -




"The Required annotation tells EF that a particular property is
required.



Adding Required to the Title property will force EF (and MVC) to
ensure that the property has data in it."




so you have to decide, if you want [Required] annotation then it means it will not allow nullable property. And if you are okay with null value then remove [Required] annotation.






share|improve this answer

























  • The property should not be null. It is the ID of a required associated entity. The association is established through the assignment of an instance to the virtual property for the associated entity. The entity framework then populates the ID on its side during the call to SaveChanges. Which it does if it gets passed its own validation.

    – denver
    Mar 28 at 18:09











  • if you change it from nullable<long>(long?) to long, it will set it to 0 by default and EF automatically assigns proper id on save.

    – Milan Raval
    Mar 28 at 18:20












  • Maybe, not sure if that will provide the desired behavior. I'll have to test. The issue could be that 0 is a valid value pointing to a separate record. I'm not sure how entity framework would know if it is support to point to record 0 or assign the value from a new record being inserted.

    – denver
    Mar 28 at 20:14











  • @denver - When you will set navigation property (virtual property) to instance EF will set foreign key correctly to the id created for the referenced record. Try it.

    – Milan Raval
    Mar 29 at 12:58











  • Tested it, per my last comment if you set the id to 0 entity framework has an issue and throws an exception. This does not surprise me because entity framework is being supplied with conflicting information. I assume because the foreign key has an id implying it is already in the database while the navigation property (virtual property) instance is not and does not have an id.

    – denver
    Mar 29 at 16:38


















0
















There can be two scenarios:



First: EntityB already existed in the database and you are pointing the EntityBId of the EntityB to the EntityBId ForeignKey of the new EntityA as follows and in this case only EntityA will be inserted to the database:



EntityB entityB = dbContext.EntityBs.FirstOrDefault(yourCondition) 

EntityA entityA = new EntityA();
entityA.EntityBId = entityB.EntityBId; // <-- assign `ForeignKey` value instead of navigation property value, hence no required validation error will occur

dbContext.EntityAs.Add(entityA);
dbContext.SaveChanges();


Second: EntityB is not already existed in the database and it will be newly inserted to the database along with EntityA. So in this case your code should be as follows:



EntityB entityB = new EntityB();
dbContext.EntityBs.Add(entityB);

EntityA entityA = new EntityA();
entityA.EntityBId = entityB.EntityBId; // <-- assign `ForeignKey` value instead of navigation property value, hence no required validation error will occur
dbContext.EntityAs.Add(entityA);
dbContext.SaveChanges();


Now decide what is your scenario and do accordingly.






share|improve this answer



























  • The second situation is in play. The code you provide will not work because entityB.EntityBId is null until the call to SaveChanges.

    – denver
    Mar 29 at 16:27











  • @denver The code you provide will not work because entityB.EntityBId is null - No! it will work. EF is smart enough to maintain this during insert.

    – TanvirArjel
    Mar 29 at 16:28












  • Try your code. You are setting entityA.EntityBId = null (this line does nothing). Validation will then fail because EntityBId is marked required. If EntityBId was not marked required entity framework would establish the relationship during insert.

    – denver
    Mar 29 at 16:42












  • @denver Is not EntityBId a auto incremented primary key?

    – TanvirArjel
    Mar 29 at 16:57











  • EntityBId is the primary key, I believe it is auto incremented by default.

    – denver
    Mar 29 at 17:04













Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);














draft saved

draft discarded
















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55403805%2frequired-associated-entity-causing-validation-errors%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









0
















See this link for usage of Required annotation: https://docs.microsoft.com/en-us/ef/ef6/modeling/code-first/data-annotations -




"The Required annotation tells EF that a particular property is
required.



Adding Required to the Title property will force EF (and MVC) to
ensure that the property has data in it."




so you have to decide, if you want [Required] annotation then it means it will not allow nullable property. And if you are okay with null value then remove [Required] annotation.






share|improve this answer

























  • The property should not be null. It is the ID of a required associated entity. The association is established through the assignment of an instance to the virtual property for the associated entity. The entity framework then populates the ID on its side during the call to SaveChanges. Which it does if it gets passed its own validation.

    – denver
    Mar 28 at 18:09











  • if you change it from nullable<long>(long?) to long, it will set it to 0 by default and EF automatically assigns proper id on save.

    – Milan Raval
    Mar 28 at 18:20












  • Maybe, not sure if that will provide the desired behavior. I'll have to test. The issue could be that 0 is a valid value pointing to a separate record. I'm not sure how entity framework would know if it is support to point to record 0 or assign the value from a new record being inserted.

    – denver
    Mar 28 at 20:14











  • @denver - When you will set navigation property (virtual property) to instance EF will set foreign key correctly to the id created for the referenced record. Try it.

    – Milan Raval
    Mar 29 at 12:58











  • Tested it, per my last comment if you set the id to 0 entity framework has an issue and throws an exception. This does not surprise me because entity framework is being supplied with conflicting information. I assume because the foreign key has an id implying it is already in the database while the navigation property (virtual property) instance is not and does not have an id.

    – denver
    Mar 29 at 16:38















0
















See this link for usage of Required annotation: https://docs.microsoft.com/en-us/ef/ef6/modeling/code-first/data-annotations -




"The Required annotation tells EF that a particular property is
required.



Adding Required to the Title property will force EF (and MVC) to
ensure that the property has data in it."




so you have to decide, if you want [Required] annotation then it means it will not allow nullable property. And if you are okay with null value then remove [Required] annotation.






share|improve this answer

























  • The property should not be null. It is the ID of a required associated entity. The association is established through the assignment of an instance to the virtual property for the associated entity. The entity framework then populates the ID on its side during the call to SaveChanges. Which it does if it gets passed its own validation.

    – denver
    Mar 28 at 18:09











  • if you change it from nullable<long>(long?) to long, it will set it to 0 by default and EF automatically assigns proper id on save.

    – Milan Raval
    Mar 28 at 18:20












  • Maybe, not sure if that will provide the desired behavior. I'll have to test. The issue could be that 0 is a valid value pointing to a separate record. I'm not sure how entity framework would know if it is support to point to record 0 or assign the value from a new record being inserted.

    – denver
    Mar 28 at 20:14











  • @denver - When you will set navigation property (virtual property) to instance EF will set foreign key correctly to the id created for the referenced record. Try it.

    – Milan Raval
    Mar 29 at 12:58











  • Tested it, per my last comment if you set the id to 0 entity framework has an issue and throws an exception. This does not surprise me because entity framework is being supplied with conflicting information. I assume because the foreign key has an id implying it is already in the database while the navigation property (virtual property) instance is not and does not have an id.

    – denver
    Mar 29 at 16:38













0














0










0









See this link for usage of Required annotation: https://docs.microsoft.com/en-us/ef/ef6/modeling/code-first/data-annotations -




"The Required annotation tells EF that a particular property is
required.



Adding Required to the Title property will force EF (and MVC) to
ensure that the property has data in it."




so you have to decide, if you want [Required] annotation then it means it will not allow nullable property. And if you are okay with null value then remove [Required] annotation.






share|improve this answer













See this link for usage of Required annotation: https://docs.microsoft.com/en-us/ef/ef6/modeling/code-first/data-annotations -




"The Required annotation tells EF that a particular property is
required.



Adding Required to the Title property will force EF (and MVC) to
ensure that the property has data in it."




so you have to decide, if you want [Required] annotation then it means it will not allow nullable property. And if you are okay with null value then remove [Required] annotation.







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 28 at 18:04









Milan RavalMilan Raval

1,4721 gold badge14 silver badges30 bronze badges




1,4721 gold badge14 silver badges30 bronze badges















  • The property should not be null. It is the ID of a required associated entity. The association is established through the assignment of an instance to the virtual property for the associated entity. The entity framework then populates the ID on its side during the call to SaveChanges. Which it does if it gets passed its own validation.

    – denver
    Mar 28 at 18:09











  • if you change it from nullable<long>(long?) to long, it will set it to 0 by default and EF automatically assigns proper id on save.

    – Milan Raval
    Mar 28 at 18:20












  • Maybe, not sure if that will provide the desired behavior. I'll have to test. The issue could be that 0 is a valid value pointing to a separate record. I'm not sure how entity framework would know if it is support to point to record 0 or assign the value from a new record being inserted.

    – denver
    Mar 28 at 20:14











  • @denver - When you will set navigation property (virtual property) to instance EF will set foreign key correctly to the id created for the referenced record. Try it.

    – Milan Raval
    Mar 29 at 12:58











  • Tested it, per my last comment if you set the id to 0 entity framework has an issue and throws an exception. This does not surprise me because entity framework is being supplied with conflicting information. I assume because the foreign key has an id implying it is already in the database while the navigation property (virtual property) instance is not and does not have an id.

    – denver
    Mar 29 at 16:38

















  • The property should not be null. It is the ID of a required associated entity. The association is established through the assignment of an instance to the virtual property for the associated entity. The entity framework then populates the ID on its side during the call to SaveChanges. Which it does if it gets passed its own validation.

    – denver
    Mar 28 at 18:09











  • if you change it from nullable<long>(long?) to long, it will set it to 0 by default and EF automatically assigns proper id on save.

    – Milan Raval
    Mar 28 at 18:20












  • Maybe, not sure if that will provide the desired behavior. I'll have to test. The issue could be that 0 is a valid value pointing to a separate record. I'm not sure how entity framework would know if it is support to point to record 0 or assign the value from a new record being inserted.

    – denver
    Mar 28 at 20:14











  • @denver - When you will set navigation property (virtual property) to instance EF will set foreign key correctly to the id created for the referenced record. Try it.

    – Milan Raval
    Mar 29 at 12:58











  • Tested it, per my last comment if you set the id to 0 entity framework has an issue and throws an exception. This does not surprise me because entity framework is being supplied with conflicting information. I assume because the foreign key has an id implying it is already in the database while the navigation property (virtual property) instance is not and does not have an id.

    – denver
    Mar 29 at 16:38
















The property should not be null. It is the ID of a required associated entity. The association is established through the assignment of an instance to the virtual property for the associated entity. The entity framework then populates the ID on its side during the call to SaveChanges. Which it does if it gets passed its own validation.

– denver
Mar 28 at 18:09





The property should not be null. It is the ID of a required associated entity. The association is established through the assignment of an instance to the virtual property for the associated entity. The entity framework then populates the ID on its side during the call to SaveChanges. Which it does if it gets passed its own validation.

– denver
Mar 28 at 18:09













if you change it from nullable<long>(long?) to long, it will set it to 0 by default and EF automatically assigns proper id on save.

– Milan Raval
Mar 28 at 18:20






if you change it from nullable<long>(long?) to long, it will set it to 0 by default and EF automatically assigns proper id on save.

– Milan Raval
Mar 28 at 18:20














Maybe, not sure if that will provide the desired behavior. I'll have to test. The issue could be that 0 is a valid value pointing to a separate record. I'm not sure how entity framework would know if it is support to point to record 0 or assign the value from a new record being inserted.

– denver
Mar 28 at 20:14





Maybe, not sure if that will provide the desired behavior. I'll have to test. The issue could be that 0 is a valid value pointing to a separate record. I'm not sure how entity framework would know if it is support to point to record 0 or assign the value from a new record being inserted.

– denver
Mar 28 at 20:14













@denver - When you will set navigation property (virtual property) to instance EF will set foreign key correctly to the id created for the referenced record. Try it.

– Milan Raval
Mar 29 at 12:58





@denver - When you will set navigation property (virtual property) to instance EF will set foreign key correctly to the id created for the referenced record. Try it.

– Milan Raval
Mar 29 at 12:58













Tested it, per my last comment if you set the id to 0 entity framework has an issue and throws an exception. This does not surprise me because entity framework is being supplied with conflicting information. I assume because the foreign key has an id implying it is already in the database while the navigation property (virtual property) instance is not and does not have an id.

– denver
Mar 29 at 16:38





Tested it, per my last comment if you set the id to 0 entity framework has an issue and throws an exception. This does not surprise me because entity framework is being supplied with conflicting information. I assume because the foreign key has an id implying it is already in the database while the navigation property (virtual property) instance is not and does not have an id.

– denver
Mar 29 at 16:38













0
















There can be two scenarios:



First: EntityB already existed in the database and you are pointing the EntityBId of the EntityB to the EntityBId ForeignKey of the new EntityA as follows and in this case only EntityA will be inserted to the database:



EntityB entityB = dbContext.EntityBs.FirstOrDefault(yourCondition) 

EntityA entityA = new EntityA();
entityA.EntityBId = entityB.EntityBId; // <-- assign `ForeignKey` value instead of navigation property value, hence no required validation error will occur

dbContext.EntityAs.Add(entityA);
dbContext.SaveChanges();


Second: EntityB is not already existed in the database and it will be newly inserted to the database along with EntityA. So in this case your code should be as follows:



EntityB entityB = new EntityB();
dbContext.EntityBs.Add(entityB);

EntityA entityA = new EntityA();
entityA.EntityBId = entityB.EntityBId; // <-- assign `ForeignKey` value instead of navigation property value, hence no required validation error will occur
dbContext.EntityAs.Add(entityA);
dbContext.SaveChanges();


Now decide what is your scenario and do accordingly.






share|improve this answer



























  • The second situation is in play. The code you provide will not work because entityB.EntityBId is null until the call to SaveChanges.

    – denver
    Mar 29 at 16:27











  • @denver The code you provide will not work because entityB.EntityBId is null - No! it will work. EF is smart enough to maintain this during insert.

    – TanvirArjel
    Mar 29 at 16:28












  • Try your code. You are setting entityA.EntityBId = null (this line does nothing). Validation will then fail because EntityBId is marked required. If EntityBId was not marked required entity framework would establish the relationship during insert.

    – denver
    Mar 29 at 16:42












  • @denver Is not EntityBId a auto incremented primary key?

    – TanvirArjel
    Mar 29 at 16:57











  • EntityBId is the primary key, I believe it is auto incremented by default.

    – denver
    Mar 29 at 17:04















0
















There can be two scenarios:



First: EntityB already existed in the database and you are pointing the EntityBId of the EntityB to the EntityBId ForeignKey of the new EntityA as follows and in this case only EntityA will be inserted to the database:



EntityB entityB = dbContext.EntityBs.FirstOrDefault(yourCondition) 

EntityA entityA = new EntityA();
entityA.EntityBId = entityB.EntityBId; // <-- assign `ForeignKey` value instead of navigation property value, hence no required validation error will occur

dbContext.EntityAs.Add(entityA);
dbContext.SaveChanges();


Second: EntityB is not already existed in the database and it will be newly inserted to the database along with EntityA. So in this case your code should be as follows:



EntityB entityB = new EntityB();
dbContext.EntityBs.Add(entityB);

EntityA entityA = new EntityA();
entityA.EntityBId = entityB.EntityBId; // <-- assign `ForeignKey` value instead of navigation property value, hence no required validation error will occur
dbContext.EntityAs.Add(entityA);
dbContext.SaveChanges();


Now decide what is your scenario and do accordingly.






share|improve this answer



























  • The second situation is in play. The code you provide will not work because entityB.EntityBId is null until the call to SaveChanges.

    – denver
    Mar 29 at 16:27











  • @denver The code you provide will not work because entityB.EntityBId is null - No! it will work. EF is smart enough to maintain this during insert.

    – TanvirArjel
    Mar 29 at 16:28












  • Try your code. You are setting entityA.EntityBId = null (this line does nothing). Validation will then fail because EntityBId is marked required. If EntityBId was not marked required entity framework would establish the relationship during insert.

    – denver
    Mar 29 at 16:42












  • @denver Is not EntityBId a auto incremented primary key?

    – TanvirArjel
    Mar 29 at 16:57











  • EntityBId is the primary key, I believe it is auto incremented by default.

    – denver
    Mar 29 at 17:04













0














0










0









There can be two scenarios:



First: EntityB already existed in the database and you are pointing the EntityBId of the EntityB to the EntityBId ForeignKey of the new EntityA as follows and in this case only EntityA will be inserted to the database:



EntityB entityB = dbContext.EntityBs.FirstOrDefault(yourCondition) 

EntityA entityA = new EntityA();
entityA.EntityBId = entityB.EntityBId; // <-- assign `ForeignKey` value instead of navigation property value, hence no required validation error will occur

dbContext.EntityAs.Add(entityA);
dbContext.SaveChanges();


Second: EntityB is not already existed in the database and it will be newly inserted to the database along with EntityA. So in this case your code should be as follows:



EntityB entityB = new EntityB();
dbContext.EntityBs.Add(entityB);

EntityA entityA = new EntityA();
entityA.EntityBId = entityB.EntityBId; // <-- assign `ForeignKey` value instead of navigation property value, hence no required validation error will occur
dbContext.EntityAs.Add(entityA);
dbContext.SaveChanges();


Now decide what is your scenario and do accordingly.






share|improve this answer















There can be two scenarios:



First: EntityB already existed in the database and you are pointing the EntityBId of the EntityB to the EntityBId ForeignKey of the new EntityA as follows and in this case only EntityA will be inserted to the database:



EntityB entityB = dbContext.EntityBs.FirstOrDefault(yourCondition) 

EntityA entityA = new EntityA();
entityA.EntityBId = entityB.EntityBId; // <-- assign `ForeignKey` value instead of navigation property value, hence no required validation error will occur

dbContext.EntityAs.Add(entityA);
dbContext.SaveChanges();


Second: EntityB is not already existed in the database and it will be newly inserted to the database along with EntityA. So in this case your code should be as follows:



EntityB entityB = new EntityB();
dbContext.EntityBs.Add(entityB);

EntityA entityA = new EntityA();
entityA.EntityBId = entityB.EntityBId; // <-- assign `ForeignKey` value instead of navigation property value, hence no required validation error will occur
dbContext.EntityAs.Add(entityA);
dbContext.SaveChanges();


Now decide what is your scenario and do accordingly.







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 29 at 0:51

























answered Mar 29 at 0:44









TanvirArjelTanvirArjel

12.7k4 gold badges22 silver badges56 bronze badges




12.7k4 gold badges22 silver badges56 bronze badges















  • The second situation is in play. The code you provide will not work because entityB.EntityBId is null until the call to SaveChanges.

    – denver
    Mar 29 at 16:27











  • @denver The code you provide will not work because entityB.EntityBId is null - No! it will work. EF is smart enough to maintain this during insert.

    – TanvirArjel
    Mar 29 at 16:28












  • Try your code. You are setting entityA.EntityBId = null (this line does nothing). Validation will then fail because EntityBId is marked required. If EntityBId was not marked required entity framework would establish the relationship during insert.

    – denver
    Mar 29 at 16:42












  • @denver Is not EntityBId a auto incremented primary key?

    – TanvirArjel
    Mar 29 at 16:57











  • EntityBId is the primary key, I believe it is auto incremented by default.

    – denver
    Mar 29 at 17:04

















  • The second situation is in play. The code you provide will not work because entityB.EntityBId is null until the call to SaveChanges.

    – denver
    Mar 29 at 16:27











  • @denver The code you provide will not work because entityB.EntityBId is null - No! it will work. EF is smart enough to maintain this during insert.

    – TanvirArjel
    Mar 29 at 16:28












  • Try your code. You are setting entityA.EntityBId = null (this line does nothing). Validation will then fail because EntityBId is marked required. If EntityBId was not marked required entity framework would establish the relationship during insert.

    – denver
    Mar 29 at 16:42












  • @denver Is not EntityBId a auto incremented primary key?

    – TanvirArjel
    Mar 29 at 16:57











  • EntityBId is the primary key, I believe it is auto incremented by default.

    – denver
    Mar 29 at 17:04
















The second situation is in play. The code you provide will not work because entityB.EntityBId is null until the call to SaveChanges.

– denver
Mar 29 at 16:27





The second situation is in play. The code you provide will not work because entityB.EntityBId is null until the call to SaveChanges.

– denver
Mar 29 at 16:27













@denver The code you provide will not work because entityB.EntityBId is null - No! it will work. EF is smart enough to maintain this during insert.

– TanvirArjel
Mar 29 at 16:28






@denver The code you provide will not work because entityB.EntityBId is null - No! it will work. EF is smart enough to maintain this during insert.

– TanvirArjel
Mar 29 at 16:28














Try your code. You are setting entityA.EntityBId = null (this line does nothing). Validation will then fail because EntityBId is marked required. If EntityBId was not marked required entity framework would establish the relationship during insert.

– denver
Mar 29 at 16:42






Try your code. You are setting entityA.EntityBId = null (this line does nothing). Validation will then fail because EntityBId is marked required. If EntityBId was not marked required entity framework would establish the relationship during insert.

– denver
Mar 29 at 16:42














@denver Is not EntityBId a auto incremented primary key?

– TanvirArjel
Mar 29 at 16:57





@denver Is not EntityBId a auto incremented primary key?

– TanvirArjel
Mar 29 at 16:57













EntityBId is the primary key, I believe it is auto incremented by default.

– denver
Mar 29 at 17:04





EntityBId is the primary key, I believe it is auto incremented by default.

– denver
Mar 29 at 17:04


















draft saved

draft discarded















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55403805%2frequired-associated-entity-causing-validation-errors%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript