sequence contains more than one element code first add-migration - ef-code-first

The below is the entity, when I am going to add-migration, it is giving me exception.
public class MyEntity
[Key]
public int ID { get; set; }
public string Name { get; set; }
[NotMapped]
public HttpPostedFileBase DiagramFMCDocumentUpload { get; set; }
//[ForeignKey("DiagramFMCDocumentID")]
//public Document DiagramFMCDocument { get; set; }
//public int? DiagramFMCDocumentID { get; set; }
//[NotMapped]
//public HttpPostedFileBase ExecutedDeedDocumentUpload { get; set; }
public Document ExecutedDeedDocument { get; set; }
[ForeignKey("ExecutedDeedDocument")]
[InverseProperty("ExecutedDeedDocument")]
public int? ExecutedDeedDocumentID { get; set; }
[NotMapped]
public HttpPostedFileBase DCertificationDocumentUpload { get; set; }
public Document DCertificationDocument { get; set; }
[ForeignKey("DCertificationDocument")]
[InverseProperty("DCertificationDocument")]
public int? DCertificationDocumentID { get; set; }
////ForeignFundBasicType
//public int ForeignFundStructureTypeFDID { get; set; }
}
When I am commenting out some Document & FOreignKey fields, it perfects fine but more than one foreign key it is not working fine. Here's the exception.
System.InvalidOperationException: Sequence contains more than one element
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.<>c__DisplayClass293.<>c__DisplayClass295.<FindRenamedIndexes>b__28b(String c)
at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()
at System.Linq.Enumerable.SequenceEqual[TSource](IEnumerable`1 first, IEnumerable`1 second, IEqualityComparer`1 comparer)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.<>c__DisplayClass293.<FindRenamedIndexes>b__28a(<>f__AnonymousType30`2 <>h__TransparentIdentifier286)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(ModelMetadata source, ModelMetadata target, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(XDocument sourceModel, XDocument targetModel, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
at System.Data.Entity.Migrations.DbMigrator.Scaffold(String migrationName, String namespace, Boolean ignoreChanges)
at System.Data.Entity.Migrations.Design.MigrationScaffolder.Scaffold(String migrationName, Boolean ignoreChanges)
at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Scaffold(MigrationScaffolder scaffolder)
at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Scaffold(String migrationName, String language, String rootNamespace, Boolean ignoreChanges)
at System.Data.Entity.Migrations.AddMigrationCommand.Execute(String name, Boolean force, Boolean ignoreChanges)
at System.Data.Entity.Migrations.AddMigrationCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Sequence contains more than one element
PM> Add-Migration First -Force
System.InvalidOperationException: Sequence contains more than one element
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.<>c__DisplayClass293.<>c__DisplayClass295.<FindRenamedIndexes>b__28b(String c)
at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()
at System.Linq.Enumerable.SequenceEqual[TSource](IEnumerable`1 first, IEnumerable`1 second, IEqualityComparer`1 comparer)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.<>c__DisplayClass293.<FindRenamedIndexes>b__28a(<>f__AnonymousType30`2 <>h__TransparentIdentifier286)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(ModelMetadata source, ModelMetadata target, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
at System.Data.Entity.Migrations.Infrastructure.EdmModelDiffer.Diff(XDocument sourceModel, XDocument targetModel, Lazy`1 modificationCommandTreeGenerator, MigrationSqlGenerator migrationSqlGenerator, String sourceModelVersion, String targetModelVersion)
at System.Data.Entity.Migrations.DbMigrator.Scaffold(String migrationName, String namespace, Boolean ignoreChanges)
at System.Data.Entity.Migrations.Design.MigrationScaffolder.Scaffold(String migrationName, Boolean ignoreChanges)
at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Scaffold(MigrationScaffolder scaffolder)
at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.Scaffold(String migrationName, String language, String rootNamespace, Boolean ignoreChanges)
at System.Data.Entity.Migrations.AddMigrationCommand.Execute(String name, Boolean force, Boolean ignoreChanges)
at System.Data.Entity.Migrations.AddMigrationCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)

What is the version of EF you use? I guess that you are using a version earlier than 6.1.3
according to this issue, I think updating 'Entity Framework' will fix your problem

Related

How can I fully instantiate the Photo Entity

public class Child
{
public int Cld { get; set; }
public string ChildCode { get; set; }
public string FirstName { get; set; }
public string SurName { get; set; }
public string Sex { get; set; }
public DateTime DateOfBirth { get; set; }
public DateTime FoundRelinguished { get; set; }
public DateTime Intake { get; set; }=DateTime.Now;
public ICollection<ChildPhoto> ChildPhotos {get; set;}
}
public class ChildPhoto
{
[Key]
public int PhotocId { get; set;}
public string FileName {get; set;}
public string PhotoPath {get; set;}
public bool IsMain {get; set;}
public int ChildId {get; set;}
public Child Child {get; set;}
public DateTime UploadDate {get; set;}=DateTime.Now;
}
public interface IChildRepository
{
Task<Child> GetChildByIdAsync(int chd);
Task<Child> AddChildrenAsync(Child child);
Task<bool> SaveAllAsync();
}
The Controller method
public async Task<ActionResult> AddPhoto(int chd, [FromForm]IFormFile file)
{
// get the child througth repository
var thechild = await _childRepository.GetChildByIdAsync(chd);
if (thechild == null)
return NotFound("The Child Adding his/her Photos was not found");
var childid = thechild.Cld;
var extension = Path.GetExtension(file.FileName);
var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
if (file == null) return BadRequest("Please Selecet a file");
if (file.Length == 0) return BadRequest("The File Your Select is Empty");
var folderName = Path.Combine(_host.WebRootPath, "ChildImages");
if (!Directory.Exists(folderName))
{
Directory.CreateDirectory(folderName);
}
string photoPath = Path.Combine(folderName, fileName);
using (var stream = new FileStream(photoPath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
var photoPathDb = Path.Combine("ChildImages", fileName );
var photo = new ChildPhoto
{
PhotoPath = photoPathDb,
FileName = fileName,
ChildId= childid
};
if (thechild.ChildPhotos.Count == 0)
{
photo.IsMain = true;
}
thechild.ChildPhotos.Add(photo);
await _childRepository.SaveAllAsync();
var photoToReturn = _mapper.Map<ChildPhoto, ChildPhotoDto>(photo);
return CreatedAtRoute("GetPhoto", new { chd = thechild.Cld, id = photo.PhotocId }, photoToReturn);
}
{
error: "details": " at API.Controllers.ChildPhotosController.AddPhoto(Int32 chd, IFormFile file) in C:\\Users\\USER\\Project\\GhAdoptionApp\\API\\Controllers\\ChildPhotosController.cs:line 82\r\n at lambda_method32(Closure , Object )\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)\r\n at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)\r\n at Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)\r\n at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)\r\n at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)\r\n at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)\r\n at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)\r\n at API.Middleware.ExceptionMiddleware.InvokeAsync(HttpContext context) in C:\\Users\\USER\\Project\\GhAdoptionApp\\API\\Middleware\\ExceptionMiddleware.cs:line 30",
"statusCode": 500,
"message": "Object reference not set to an instance of an object."
}
Please I have the entity for child and ChildPhotos,
In the Controller I was called the a child through interface and the childrepository. but I get the Object reference not set to an instance of an object error.

ASP.net Blazor: Display data from two or more related tables

https://www.youtube.com/watch?v=UBNRcaw1bDk&list=PL6n9fhu94yhVowClAs8-6nYnfsOTma14P&index=23
Hi I'm trying to implement project as mentioned in above link. I'm trying get data from ASP.NET WebAPI project and consume in Blazor project. I have no issue retrieving data from single table. But when I try to retrieve data from Secondary table . I'm getting error below:
"HttpRequestException: Response status code does not indicate success: 500 (Internal Server Error)."
I tried casting the result (in API project)explicitly to 'Employee' class before sending. Didn't work. Debug on API clearly shows returning Employee with Department information but on Blazor project while receiving getting error. Thanks in advance!!
UPDATE:
Thank you all for offering help. Here is the original code.
Models:
public class Employee
{
public int EmployeeId { get; set; }
[Required]
[MinLength(2)]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public string Email { get; set; }
public DateTime DateOfBrith { get; set; }
public Gender Gender { get; set; }
public int DepartmentId { get; set; }
public Department Department { get; set; }
public string PhotoPath { get; set; }
}
public class Department
{
public int DepartmentId { get; set; }
public string DepartmentName { get; set; }
}
EF:
public class EmployeeRepository : IEmployeeRepository
{
private readonly AppDbContext appDbContext;
public EmployeeRepository(AppDbContext appDbContext)
{
this.appDbContext = appDbContext;
}
public async Task<Employee> GetEmployee(int employeeId)
{
// If I don't include Department table. I'm able to retrieve employee table data fine in Blazor project
return await appDbContext.Employees
.Include(e => e.Department)
.FirstOrDefaultAsync(e => e.EmployeeId == employeeId);
}
}
API:
[Route("api/[controller]")]
[ApiController]
public class EmployeesController : ControllerBase
{
private readonly IEmployeeRepository employeeRepository;
public EmployeesController(IEmployeeRepository employeeRepository)
{
this.employeeRepository = employeeRepository;
}
[HttpGet("{id:int}")]
public async Task<ActionResult<Employee>> GetEmployee(int id)
{
try
{
var result = await employeeRepository.GetEmployee(id);
if (result == null) return NotFound();
//Breakpoint here returns data perfectly fine . With or without cast
return Ok(result);
}
catch (Exception)
{
return StatusCode(StatusCodes.Status500InternalServerError,
"Error retrieving data from the database");
}
}
}
Call API in Blazor
//Service
public interface IEmployeeService
{
Task<Employee> GetEmployee(int id);
}
public class EmployeeService : IEmployeeService
{
private readonly HttpClient httpClient;
public EmployeeService(HttpClient httpClient)
{
this.httpClient = httpClient;
}
public async Task<Employee> GetEmployee(int id)
{
//Error on receiving end
return await httpClient.GetJsonAsync<Employee>($"api/employees/{id}");
}
}
//Blazor Component Base class
namespace EmployeeManagement.Web.Pages
{
public class EmployeeDetailsBase : ComponentBase
{
public Employee Employee { get; set; } = new Employee();
[Inject]
public IEmployeeService EmployeeService { get; set; }
[Parameter]
public string Id { get; set; }
protected async override Task OnInitializedAsync()
{
Id = Id ?? "1";
Employee = await EmployeeService.GetEmployee(int.Parse(Id));
}
}
}
// configuring in startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddHttpClient<IEmployeeService, EmployeeService>(client =>
{
client.BaseAddress = new Uri("https://localhost:44379/");
});
}
Error:
HttpRequestException: Response status code does not indicate success: 500 (Internal Server Error).
System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
System.Net.Http.HttpClient.GetStringAsyncCore(Task<HttpResponseMessage> getTask)
Microsoft.AspNetCore.Components.HttpClientJsonExtensions.GetJsonAsync<T>(HttpClient httpClient, string requestUri)
XXXX.Services.EmployeeService.GetEmployee(int id) in EmployeeService.cs
+
var item = await httpClient.GetJsonAsync<Employee>($"api/Employees/{id}");
XXXX.Pages.EmployeeDetailsBase.OnInitializedAsync() in EmployeeDetailsBase.cs
+
Employee = await EmployeeService.GetEmployee(int.Parse(Id));
Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle)
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.HandleException(Exception exception)
Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle)
Microsoft.AspNetCore.Components.RenderTree.Renderer.ProcessAsynchronousWork()
Microsoft.AspNetCore.Components.RenderTree.Renderer.RenderRootComponentAsync(int componentId, ParameterView initialParameters)
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.CreateInitialRenderAsync(Type componentType, ParameterView initialParameters)
Microsoft.AspNetCore.Components.Rendering.HtmlRenderer.RenderComponentAsync(Type componentType, ParameterView initialParameters)
Microsoft.AspNetCore.Components.Rendering.RendererSynchronizationContext+<>c__11<TResult>+<<InvokeAsync>b__11_0>d.MoveNext()
Microsoft.AspNetCore.Mvc.ViewFeatures.StaticComponentRenderer.PrerenderComponentAsync(ParameterView parameters, HttpContext httpContext, Type componentType)
Microsoft.AspNetCore.Mvc.ViewFeatures.ComponentRenderer.PrerenderedServerComponentAsync(HttpContext context, ServerComponentInvocationSequence invocationId, Type type, ParameterView parametersCollection)
Microsoft.AspNetCore.Mvc.ViewFeatures.ComponentRenderer.RenderComponentAsync(ViewContext viewContext, Type componentType, RenderMode renderMode, object parameters)
Microsoft.AspNetCore.Mvc.TagHelpers.ComponentTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.<RunAsync>g__Awaited|0_0(Task task, TagHelperExecutionContext executionContext, int i, int count)
Praxis.EGPSystemBlazor.Pages.Pages__Host.<ExecuteAsync>b__14_1() in _Host.cshtml
+
<component type="typeof(App)" render-mode="ServerPrerendered" />
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.SetOutputContentAsync()
Praxis.EGPSystemBlazor.Pages.Pages__Host.ExecuteAsync() in _Host.cshtml
+
Layout = null;
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageCoreAsync(IRazorPage page, ViewContext context)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderPageAsync(IRazorPage page, ViewContext context, bool invokeViewStarts)
Microsoft.AspNetCore.Mvc.Razor.RazorView.RenderAsync(ViewContext context)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.ViewFeatures.ViewExecutor.ExecuteAsync(ViewContext viewContext, string contentType, Nullable<int> statusCode)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0<TFilter, TFilterAsync>(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext<TFilter, TFilterAsync>(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeResultFilters>g__Awaited|27_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Update :
Thanks all for response. Department is mandatory.So there is no chance of null. This is the only solution that worked. I have created another Viewmodel in Blazor project that has all fields same as Employee and Initialized Department inside ViewModelClass. Then I was able to show Employee.Department.DepartmentName in UI.
public class EmployeeViewModel
{
public int EmployeeId { get; set; }
[Required]
[MinLength(2)]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public string Email { get; set; }
public string ConfirmEmail { get; set; }
public DateTime DateOfBrith { get; set; }
public Gender Gender { get; set; }
public int DepartmentId { get; set; }
public Department Department { get; set; }= new Department();
public string PhotoPath { get; set; }
}
Is the web API project also loading as well as the client project in the web browser?
If not you may need to go to the properties of your solution from solution Explorer to launch multiple projects.
It may be a good idea to navigate to the web API and type in the following string into the address bar after the port number:
/api/employees/1
Then if the browser displays Json then all is okay. Otherwise you can set a breakpoint in your web API and further investigate where the error is occurring.
You may want to use something like Postman to test the web API.

System.InvalidOperationException: 'No 'id' member found on type

I'm getting this error only on release build of xamarin forms IOS.
App.xaml.cs
public partial class App : Application
{
public static MobileServiceClient MobileService = new MobileServiceClient(B2CConstants.ApplicationURL, new HttpClientHandler());
public static BaseViewModel BaseViewModel = new BaseViewModel();
public static ShapeTypeViewModel ShapeTypeViewModel = new ShapeTypeViewModel();
public static HoleDataViewModel HoleMapViewModel = new HoleDataViewModel();
public static PlayersViewModel PlayersViewModel = new PlayersViewModel();
public static RoundsViewModel RoundsViewModel = new RoundsViewModel();
public static ScoresViewModel ScoresViewModel = new ScoresViewModel();
public static TeeTimesViewModel TeeTimesViewModel = new TeeTimesViewModel();
public static TournamentViewModel TournamentSamplesViewModel = new TournamentViewModel();
public static ShapesViewModel ShapeViewModel = new ShapesViewModel();
public static MyTournamentsViewModel MyTournamentsViewModel = new MyTournamentsViewModel();
public static MyTournamentCoursesViewModel MyTournamentCoursesViewModel = new MyTournamentCoursesViewModel();
public static MyTournamentPlayersViewModel MyTournamentPlayersViewModel = new MyTournamentPlayersViewModel();
public static MyTournamentLeaderboardViewModel MyTournamentLeaderboardViewModel = new MyTournamentLeaderboardViewModel();
public static MyTournamentRoundsViewModel MyTournamentRoundsViewModel = new MyTournamentRoundsViewModel();
public static MyTournamentScoresViewModel MyTournamentScoresViewModel = new MyTournamentScoresViewModel();
public static MyTournamentYardagesViewModel MyTournamentYardagesViewModel = new MyTournamentYardagesViewModel();
Whatever viewmodel is called first (that calls azure mobile services)- causes the error.
ShapesViewModel.cs
public class ShapesViewModel : BaseViewModel
{
public MobileServiceCollection<GeoPosShapes, GeoPosShapes> shapeItems;
public IMobileServiceSyncTable<AzureShapes> ShapesTable = App.MobileService.GetSyncTable<AzureShapes>(); // offline sync
The error occurs on calling
GetSyncTable(Tablename).
Shapes.cs
namespace RangeFinder.Models
{
public class AzureShapes
{
public string id { get; set; }
public int shapetypeid { get; set; }
public string courseid { get; set; }
[JsonProperty(PropertyName = "wkt")]
public string WKT { get; set; }
[JsonProperty(PropertyName = "hole")]
public int Hole { get; set; }
}
public class GeoPosShapes
{
public string id { get; set; }
public int shapetypeid { get; set; }
public string courseid { get; set; }
[JsonProperty(PropertyName = "hole")]
public int Hole { get; set; }
public List<Position> PolyGeoPos { get; set; }
//public MapElement mapElement { get; set; }
}
}
The error message is:
The thread 0x6 has exited with code 0 (0x0).
2020-06-18 22:44:36.650 RangeFinder.iOS[571:98215] System.TypeInitializationException: The type initializer for 'RangeFinder.App' threw an exception. ---> System.InvalidOperationException: No 'id' member found on type 'RangeFinder.Models.ShapeTypes'.
at Microsoft.WindowsAzure.MobileServices.MobileServiceContractResolver.DetermineIdProperty (System.Type type, System.Collections.Generic.IEnumerable`1[T] properties) [0x00070] in :0
at Microsoft.WindowsAzure.MobileServices.MobileServiceContractResolver.CreatePropertiesInner (System.Type type, Newtonsoft.Json.MemberSerialization memberSerialization) [0x00075] in :0
at Microsoft.WindowsAzure.MobileServices.MobileServiceContractResolver.CreateProperties (System.Type type, Newtonsoft.Json.MemberSerialization memberSerialization) [0x0004f] in :0
at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateObjectContract (System.Type objectType) [0x0003a]
in <2073514815234917a5e8f91b0b239405>:0
at Microsoft.WindowsAzure.MobileServices.MobileServiceContractResolver.CreateObjectContract (System.Type objectType) [0x00000] in :0
at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateContract (System.Type objectType) [0x0010f] in <2073514815234917a5e8f91b0b239405>:0
at Microsoft.WindowsAzure.MobileServices.MobileServiceContractResolver.ResolveTableName (System.Type type) [0x000ea] in :0
at Microsoft.WindowsAzure.MobileServices.MobileServiceClient.GetSyncTable[T] () [0x0000b] in :0
at RangeFinder.ViewModels.ShapeTypeViewModel..ctor () [0x00000] in C:\Users\Karl\Source\Repos\RangeFinder\RangeFinder.standard\ViewModels\ShapeTypeViewModel.cs:13
at RangeFinder.App..cctor () [0x00027] in C:\Users\Karl\Source\Repos\RangeFinder\RangeFinder.standard\Views\App.xaml.cs:36
--- End of inner exception stack trace ---
at RangeFinder.iOS.AppDelegate
.FinishedLaunching (UIKit.UIApplication app, Foundation.NSDictionary options) [0x00093] in <92430b17376a435287b491877f96ca89>:0
at (wrapper managed-to-native) UIKit.UIApplication.UIApplicationMain(int,string[],intptr,intptr)
at UIKit.UIApplication.Main (System.String[] args, System.IntPtr principal, System.IntPtr delegate) [0x00005] in /Library/Frameworks/Xamarin.iOS.framework/Versions/13.18.2.1/src/Xamarin.iOS/UIKit/UIApplication.cs:86
at UIKit.UIApplication.Main (System.String[] args, System.String principalClassName, System.String delegateClassName) [0x0000e] in /Library/Frameworks/Xamarin.iOS.framework/Versions/13.18.2.1/src/Xamarin.iOS/UIKit/UIApplication.cs:65
at RangeFinder.iOS.Application.Main (System.String[] args) [0x00000] in <92430b17376a435287b491877f96ca89>:0
System.TypeInitializationException: 'Loading...'
Any help would be appreciated - as this is the last step before getting app published on IOS AppStore
You have not given is all the types involved. See:
No 'id' member found on type 'RangeFinder.Models.ShapeTypes'.
You explicitly want to look at RangeFinder.Models.ShapeTypes type. There is no id field on that type.

Can't create one to many relationship between AspNetUsers and Custom Table

I am trying to build one to many relationship between AspnetUsers and Trip.
My Trip class is as given below:
public class Trip
{
public int TripId { get; set; }
public string TripName { get; set; }
public string ApplicationUserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
I have added following in IdentityModel:
public virtual ICollection<Trip> Trips {get; set; }
Now when I try to run this or update-database I get the following error:
System.InvalidOperationException: Multiple object sets per type are not supported. The object sets 'ApplicationUsers' and 'Users' can both contain instances of type 'IdentityRelationship.Models.ApplicationUser'
at System.Data.Entity.Internal.DbSetDiscoveryService.RegisterSets(DbModelBuilder modelBuilder)
at System.Data.Entity.Internal.LazyInternalContext.CreateModelBuilder()
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.LazyInternalContext.get_ModelBeingInitialized()
at System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(DbContext context, XmlWriter writer)
at System.Data.Entity.Utilities.DbContextExtensions.<>c__DisplayClass1.<GetModel>b__0(XmlWriter w)
at System.Data.Entity.Utilities.DbContextExtensions.GetModel(Action`1 writeXml)
at System.Data.Entity.Utilities.DbContextExtensions.GetModel(DbContext context)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration, DbContext usersContext, DatabaseExistenceState existenceState, Boolean calledByCreateDatabase)
at System.Data.Entity.Migrations.DbMigrator..ctor(DbMigrationsConfiguration configuration)
at System.Data.Entity.Migrations.Design.MigrationScaffolder..ctor(DbMigrationsConfiguration migrationsConfiguration)
at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldRunner.Run()
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.AppDomain.DoCallBack(CrossAppDomainDelegate callBackDelegate)
at System.Data.Entity.Migrations.Design.ToolingFacade.Run(BaseRunner runner)
at System.Data.Entity.Migrations.Design.ToolingFacade.ScaffoldInitialCreate(String language, String rootNamespace)
at System.Data.Entity.Migrations.EnableMigrationsCommand.<>c__DisplayClass2.<.ctor>b__0()
at System.Data.Entity.Migrations.MigrationsDomainCommand.Execute(Action command)
Multiple object sets per type are not supported. The object sets 'ApplicationUsers' and 'Users' can both contain instances of type 'IdentityRelationship.Models.ApplicationUser'.
Can anyone please tell me what's going on and how to solve this?
In my opinion class called Trip, should contains IdentityModel's foreign key virtual property (navigation property).
Fore example:
public class Trip{
public int TripId { get; set; }
public string TripName { get; set; }
public string ApplicationUserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
public int IdentityModelId{ get; set; }
[ForeignKey("IdentityModelId")]
public virtual IdentityModel IdentityModel{get; set; }
}
And afther that it should be possible to populate the collection into Trips property at IdentityModel class.

Having trouble with database first generated MVC 4 model with foreign keys

The table with multiple columns pointing to same People table i.e. person class
namespace IGRS.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public partial class HinduMarriageForm
{
public int ID { get; set; }
[ForeignKey("Person"), Column(Order=0)]
public int HusbandID { get; set; }
public int HusbandsFatherID { get; set; }
public int HusbandsMotherID { get; set; }
public int WifeID { get; set; }
public int WifesFatherID { get; set; }
public int WifesMotherID { get; set; }
public Nullable<int> HusbandsNRIInfoID { get; set; }
public Nullable<int> WifesNRIInfoID { get; set; }
public Nullable<int> PersonWhoSolemnizedMarriageID { get; set; }
public bool SolemnizedUnderSection7 { get; set; }
public bool SolemnizedUnderSection7A { get; set; }
public int MarriageVenueID { get; set; }
public System.DateTime DateOfMarriage { get; set; }
public int Witness1ID { get; set; }
public int Witness2ID { get; set; }
public int Witness3ID { get; set; }
public int SROID { get; set; }
public int SRID { get; set; }
public virtual MarriageVenue MarriageVenue { get; set; }
public virtual NRIInformation NRIInformation { get; set; }
public virtual NRIInformation NRIInformation1 { get; set; }
public virtual Person Person { get; set; }
public virtual Person Person1 { get; set; }
public virtual Person Person2 { get; set; }
public virtual Person Person3 { get; set; }
public virtual Person Person4 { get; set; }
public virtual Person Person5 { get; set; }
public virtual Person Person6 { get; set; }
public virtual Person Person7 { get; set; }
public virtual Person Person8 { get; set; }
public virtual Person Person9 { get; set; }
public virtual SR SR { get; set; }
public virtual SRO SRO { get; set; }
}
}
This is the auto generated by database first MVC4 methodology Entity Framework 5 VS2012 defaults:
namespace IGRS.Models
{
using System;
using System.Collections.Generic;
public partial class Person
{
public Person()
{
this.HinduMarriageForms = new HashSet<HinduMarriageForm>();
this.HinduMarriageForms1 = new HashSet<HinduMarriageForm>();
this.HinduMarriageForms2 = new HashSet<HinduMarriageForm>();
this.HinduMarriageForms3 = new HashSet<HinduMarriageForm>();
this.HinduMarriageForms4 = new HashSet<HinduMarriageForm>();
this.HinduMarriageForms5 = new HashSet<HinduMarriageForm>();
this.HinduMarriageForms6 = new HashSet<HinduMarriageForm>();
this.HinduMarriageForms7 = new HashSet<HinduMarriageForm>();
this.HinduMarriageForms8 = new HashSet<HinduMarriageForm>();
this.HinduMarriageForms9 = new HashSet<HinduMarriageForm>();
}
public int ID { get; set; }
public string FullName { get; set; }
public Nullable<int> ReligionID { get; set; }
public Nullable<int> CasteID { get; set; }
public Nullable<System.DateTime> DateOfBirth { get; set; }
public Nullable<int> MaritalStatusID { get; set; }
public Nullable<int> OccupationID { get; set; }
public string PermanentAddress { get; set; }
public string PassportNumber { get; set; }
public virtual Caste Caste { get; set; }
public virtual ICollection<HinduMarriageForm> HinduMarriageForms { get; set; }
public virtual ICollection<HinduMarriageForm> HinduMarriageForms1 { get; set; }
public virtual ICollection<HinduMarriageForm> HinduMarriageForms2 { get; set; }
public virtual ICollection<HinduMarriageForm> HinduMarriageForms3 { get; set; }
public virtual ICollection<HinduMarriageForm> HinduMarriageForms4 { get; set; }
public virtual ICollection<HinduMarriageForm> HinduMarriageForms5 { get; set; }
public virtual ICollection<HinduMarriageForm> HinduMarriageForms6 { get; set; }
public virtual ICollection<HinduMarriageForm> HinduMarriageForms7 { get; set; }
public virtual ICollection<HinduMarriageForm> HinduMarriageForms8 { get; set; }
public virtual ICollection<HinduMarriageForm> HinduMarriageForms9 { get; set; }
public virtual MaritalState MaritalState { get; set; }
public virtual Occupation Occupation { get; set; }
public virtual Religion Religion { get; set; }
}
}
And the NRIInformation table info:
namespace IGRS.Models
{
using System;
using System.Collections.Generic;
public partial class NRIInformation
{
public NRIInformation()
{
this.HinduMarriageForms = new HashSet<HinduMarriageForm>();
this.HinduMarriageForms1 = new HashSet<HinduMarriageForm>();
}
public int ID { get; set; }
public string PassportNumber { get; set; }
public string PassportIssuedBy { get; set; }
public System.DateTime PassportValidUpto { get; set; }
public string VisaIssued { get; set; }
public System.DateTime VisaValidUpto { get; set; }
public int TypeOfResidentID { get; set; }
public string SocialSecurityNumber { get; set; }
public virtual ICollection<HinduMarriageForm> HinduMarriageForms { get; set; }
public virtual ICollection<HinduMarriageForm> HinduMarriageForms1 { get; set; }
}
}
This upon running on the HinduMarriageForm controller code obvioous so not providing gives the error:
Server Error in '/' Application.
Invalid column name 'NRIInformation_ID'.
Invalid column name 'NRIInformation_ID1'.
Invalid column name 'NRIInformation_ID2'.
Invalid column name 'NRIInformation1_ID'.
Invalid column name 'Person_ID'.
Invalid column name 'Person_ID1'.
Invalid column name 'Person_ID2'.
Invalid column name 'Person_ID3'.
Invalid column name 'Person_ID4'.
Invalid column name 'Person_ID5'.
Invalid column name 'Person_ID6'.
Invalid column name 'Person_ID7'.
Invalid column name 'Person_ID8'.
Invalid column name 'Person_ID9'.
Invalid column name 'Person1_ID'.
Invalid column name 'Person2_ID'.
Invalid column name 'Person3_ID'.
Invalid column name 'Person4_ID'.
Invalid column name 'Person5_ID'.
Invalid column name 'Person6_ID'.
Invalid column name 'Person7_ID'.
Invalid column name 'Person8_ID'.
Invalid column name 'Person9_ID'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'NRIInformation_ID'.
Invalid column name 'NRIInformation_ID1'.
Invalid column name 'NRIInformation_ID2'.
Invalid column name 'NRIInformation1_ID'.
Invalid column name 'Person_ID'.
Invalid column name 'Person_ID1'.
Invalid column name 'Person_ID2'.
Invalid column name 'Person_ID3'.
Invalid column name 'Person_ID4'.
Invalid column name 'Person_ID5'.
Invalid column name 'Person_ID6'.
Invalid column name 'Person_ID7'.
Invalid column name 'Person_ID8'.
Invalid column name 'Person_ID9'.
Invalid column name 'Person1_ID'.
Invalid column name 'Person2_ID'.
Invalid column name 'Person3_ID'.
Invalid column name 'Person4_ID'.
Invalid column name 'Person5_ID'.
Invalid column name 'Person6_ID'.
Invalid column name 'Person7_ID'.
Invalid column name 'Person8_ID'.
Invalid column name 'Person9_ID'.
Source Error:
Line 20: {
Line 21: var hindumarriageforms = db.HinduMarriageForms.Include(h => h.MarriageVenue).Include(h => h.SR).Include(h => h.SRO);
Line 22: return View(hindumarriageforms.ToList());
Line 23: }
Line 24:
Source File: c:\Users\gilgamesh\Documents\Visual Studio 2012\Projects\IGRS\IGRS\Controllers\HinduMarriageFormController.cs Line: 22
Stack Trace:
[SqlException (0x80131904): Invalid column name 'NRIInformation_ID'.
Invalid column name 'NRIInformation_ID1'.
Invalid column name 'NRIInformation_ID2'.
Invalid column name 'NRIInformation1_ID'.
Invalid column name 'Person_ID'.
Invalid column name 'Person_ID1'.
Invalid column name 'Person_ID2'.
Invalid column name 'Person_ID3'.
Invalid column name 'Person_ID4'.
Invalid column name 'Person_ID5'.
Invalid column name 'Person_ID6'.
Invalid column name 'Person_ID7'.
Invalid column name 'Person_ID8'.
Invalid column name 'Person_ID9'.
Invalid column name 'Person1_ID'.
Invalid column name 'Person2_ID'.
Invalid column name 'Person3_ID'.
Invalid column name 'Person4_ID'.
Invalid column name 'Person5_ID'.
Invalid column name 'Person6_ID'.
Invalid column name 'Person7_ID'.
Invalid column name 'Person8_ID'.
Invalid column name 'Person9_ID'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +1767866
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +5352418
System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +244
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1691
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +61
System.Data.SqlClient.SqlDataReader.get_MetaData() +90
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +365
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) +1406
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +177
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +53
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +134
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior) +41
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior) +10
System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +437
[EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details.]
System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand entityCommand, CommandBehavior behavior) +507
System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext context, ObjectParameterCollection parameterValues) +730
System.Data.Objects.ObjectQuery1.GetResults(Nullable1 forMergeOption) +131
System.Data.Objects.ObjectQuery1.System.Collections.Generic.IEnumerable<T>.GetEnumerator() +36
System.Data.Entity.Internal.Linq.InternalQuery1.GetEnumerator() +126
System.Data.Entity.Infrastructure.DbQuery1.System.Collections.Generic.IEnumerable<TResult>.GetEnumerator() +99
System.Collections.Generic.List1..ctor(IEnumerable1 collection) +369
System.Linq.Enumerable.ToList(IEnumerable1 source) +58
IGRS.Controllers.HinduMarriageFormController.Index() in c:\Users\gilgamesh\Documents\Visual Studio 2012\Projects\IGRS\IGRS\Controllers\HinduMarriageFormController.cs:22
lambda_method(Closure , ControllerBase , Object[] ) +101
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +211
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +27
System.Web.Mvc.Async.<>c_DisplayClass42.b_41() +28
System.Web.Mvc.Async.<>c_DisplayClass81.<BeginSynchronous>b__7(IAsyncResult _) +10
System.Web.Mvc.Async.WrappedAsyncResult1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c_DisplayClass39.b_33() +57
System.Web.Mvc.Async.<>c_DisplayClass4f.b_49() +223
System.Web.Mvc.Async.<>c_DisplayClass37.b_36(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
System.Web.Mvc.Async.WrappedAsyncResult1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
System.Web.Mvc.<>c_DisplayClass1d.b_18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c_DisplayClass4.b_3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c_DisplayClass8.b_3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c_DisplayClass4.b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9514812
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18408
So far I have tried a bunch of things using ForeignKey and Column with Order decorations etc but can only reduce number of errors. I am not sure what is going on wrong with the reflection. Also here are the SQL create table scripts for the 2 foreign key tables and the source table:
CREATE TABLE [dbo].[HinduMarriageForms](
[ID] [int] IDENTITY(1,1) NOT NULL,
[HusbandID] [int] NOT NULL,
[HusbandsFatherID] [int] NOT NULL,
[HusbandsMotherID] [int] NOT NULL,
[WifeID] [int] NOT NULL,
[WifesFatherID] [int] NOT NULL,
[WifesMotherID] [int] NOT NULL,
[HusbandsNRIInfoID] [int] NULL,
[WifesNRIInfoID] [int] NULL,
[PersonWhoSolemnizedMarriageID] [int] NULL,
[SolemnizedUnderSection7] [bit] NOT NULL,
[SolemnizedUnderSection7A] [bit] NOT NULL,
[MarriageVenueID] [int] NOT NULL,
[DateOfMarriage] [datetime] NOT NULL,
[Witness1ID] [int] NOT NULL,
[Witness2ID] [int] NOT NULL,
[Witness3ID] [int] NOT NULL,
[SROID] [int] NOT NULL,
[SRID] [int] NOT NULL,
CONSTRAINT [PK_HinduMarriageForm] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[NRIInformations](
[ID] [int] IDENTITY(1,1) NOT NULL,
[PassportNumber] [nvarchar](50) NOT NULL,
[PassportIssuedBy] [nvarchar](255) NOT NULL,
[PassportValidUpto] [datetime] NOT NULL,
[VisaIssued] [nvarchar](255) NOT NULL,
[VisaValidUpto] [datetime] NOT NULL,
[TypeOfResidentID] [int] NOT NULL,
[SocialSecurityNumber] [nchar](10) NULL,
CONSTRAINT [PK_NRIInformation] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[People](
[ID] [int] IDENTITY(1,1) NOT NULL,
[FullName] [nvarchar](255) NOT NULL,
[ReligionID] [int] NULL,
[CasteID] [int] NULL,
[DateOfBirth] [datetime] NULL,
[MaritalStatusID] [int] NULL,
[OccupationID] [int] NULL,
[PermanentAddress] [nvarchar](512) NOT NULL,
[PassportNumber] [nvarchar](50) NULL,
CONSTRAINT [PK_Person] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Not pasting the foreign key SQL creation statements assume they are all there in back end sql server database.
This whole MVC 4 Entity Framework 5 project was Database First Driven and giving these errors. The simpler tables which dont have multiple columns linked to same foreign key table and column are working fine.
From this section of your error message:
Source Error:
Line 20: { Line 21: var hindumarriageforms = db.HinduMarriageForms.Include(h => h.MarriageVenue).Include(h => h.SR).Include(h => h.SRO); Line 22: return View(hindumarriageforms.ToList()); Line 23: } Line 24:
Source File: c:\Users\gilgamesh\Documents\Visual Studio 2012\Projects\IGRS\IGRS\Controllers\HinduMarriageFormController.cs Line: 22
If you also include the NRIInformation and Person tables, does the problem go away?
var hindumarriageforms = db.HinduMarriageForms.Include(h => h.MarriageVenue).Include(h => h.SR).Include(h => h.SRO).Include(h => h.Person).Include(h => h.NRIInformation);
Edit: As an aside, I usually like to rename the virtuals where instead of it being Person1, Person2, Person3... etc. Change it to PersonForHusband, PersonForHusbandsFather, PersonForHusbandsMother, etc. so that the navigation properties are clear and you don't accidentally use the wrong one. Makes programming with those classes later so much easier to use.

Resources