I have been working with EF5 trying to build an application and have run into a small problem.
I have created a model like
public class TargetBusinessModel
{
public int Id { get; set; }
public Guid BusinessId {get; set; }
public Business Business { get; set; }
public string ContactName { get; set; }
public string ContactTitle { get; set; }
public string ContactPhone { get; set; }
}
Updated the Context file
public DbSet<TargetBusinessModel> TargetBusinessModels { get; set; }
My problem is none of the properties from Business are mapped within the database.
The Business Model I am trying to add is from another project, I am not sure if that's the reason.
I don't mind if the code first creates a separate table for my Business model or combines them together.
Can anyone help out?
Try to add DbSet for Business entities to your DbContext implementation:
public DbSet<Business> Businesses { get; set; }
Related
I'm creating an ASP.NET Core 3.1 Web API using OData v4.
I just made a GitHub repo here containing the entire solution, even the database project with dummy data.
Some blogs helped me along the way:
Experimenting with OData in ASP.NET Core 3.1
Supercharging ASP.NET Core API with OData
I've successfully created 3 basic endpoints that can be queried (Countries, Cities and Customers).
The Country and City endpoints work as expected, it is the Customer endpoint that causes some issues on $expand.
The Customer model looks like this (please note that I am currently using domain entities instead of DTO's because I want to get everything working smoothly first, before projecting them to DTO's):
public abstract class AppEntity : IAppEntity
{
[Key]
public int Id { get; set; }
}
public class Customer : AppEntity
{
public string Name { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public virtual City City { get; set; }
public string VAT { get; set; }
public virtual List<CustomerEmailAddress> EmailAddresses { get; set; }
public virtual List<CustomerNote> Notes { get; set; }
}
With the following models acting as navigation properties:
public class CustomerEmailAddress : AppEntity
{
public Customer Customer { get; set; }
public string EmailAddress { get; set; }
public bool IsPrimary { get; set; }
}
public class CustomerNote : AppEntity
{
public Customer Customer { get; set; }
public DateTime DateTime { get; set; }
public string Message { get; set; }
}
Most of my queries are successful:
Just the collection: https://localhost:44309/api/customer
Expanding the City: https://localhost:44309/api/customer?$expand=City
On of the one-many relationships: https://localhost:44309/api/customer?$expand=Notes
But as soon as I try to expand 2 or more one-many properties or expand all (?$expand=*), I get an exception:
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')
Any clue where this exception might be coming from?
My EdmModel is defined as:
IEdmModel GetEdmModel()
{
var odataBuilder = new ODataConventionModelBuilder();
odataBuilder.EntitySet<Country>("Country");
odataBuilder.EntitySet<City>("City");
odataBuilder.EntitySet<Customer>("Customer");
return odataBuilder.GetEdmModel();
}
I am using VS2015 and have MVC5 web app. I want to use scaffolding feature to generate CRUD for my child entities: currently when generating the scaffolding it is NOT creating the views/edit/create for the IEnumerable collection 'Cities'.
I have googled but not found anything. Is there a Nuget package that does what I want. It should allow to add/delete/edit the cities maybe using partial view but should be auto-generated.
code:
public partial class Country
{
public int ID { get; set; }
public string Name { get; set; }
public string Color { get; set; }
public string Location { get; set; }
public virtual IEnumerable<Cities> Cities { get; set; }
}
public partial class Cities
{
public int ID { get; set; }
public string Name { get; set; }
public string TreLocation { get; set; }
public string Geo { get; set; }
}
Do you want an editable list of cities under each country?
Don't use mvc! In the time you spend figuring it out, you can probably learn angular. Which is far better for tis sort of thing.
However, back in the mists of time wise sages wrestled with this problem, for example....
Collection of complex child objects in Asp.Net MVC 3 application?
https://www.donnfelker.com/editable-grid-list-binding-in-mvc2/&ved=2ahUKEwiltefd9cngAhWjQxUIHe45AM4QFjACegQIARAB&usg=AOvVaw2z8iH5hZnObcnIMl3d4cyI
We are developing a new application using ASP.NET Core and EF Core. We're on the latest stable release (v1.1.2). We are unable to load related data via navigation properties.
I am aware that lazy loading is not supported in EF Core but every post on the subject I have looked at suggests that we should be able to explicitly load related data using .Include(). However, this is not working for us and the related entities are always null when we load them in code.
We have two entities - 'Exchange' and 'Trade'. 'Exchange' has a foreign key to 'Trade' and contains a Virtual Trade called Request and another called Offer, thus:-
[Table("Exchange")]
public partial class Exchange : BaseEntity
{
public string Pending { get; set; }
[Display(Name = "Exchange Date"), DataType(DataType.Date)]
public DateTime DateOfExchange { get; set; }
public decimal EstimatedHours { get; set; }
public decimal ActualHours { get; set; }
public string Description { get; set; }
public string FollowUp { get; set; }
public string Status { get; set; }
[ForeignKey("User")]
[Required]
public int Broker_Fk { get; set; }
public virtual User Broker { get; set; }
public int Request_Fk { get; set; }
public virtual Trade Request { get; set; }
public int Offer_Fk { get; set; }
public virtual Trade Offer { get; set; }
I have a View Model that instantiates an 'Exchange' which I know has a related 'Request':-
_vm.Exchanges = _context.Exchange.Include(i => i.Request).Where(t => t.Request.User_Fk == user.Id || t.Offer.User_Fk == user.Id).ToList();
This returns an Exchange, which I am passing to and rendering in the View Model:-
#foreach (var item in Model.Exchanges)
{
<span>#item.Request.Name</span> <br />
}
The problem is that #item.Request is null, even though I have explicitly included it when loading the Exchange. I know that there really is a related entity in existence because one of the other properties on Exchange is its foreign key, which is populated.
What am I missing? Every example I have seen posted suggests that what I've done should work.
Your model attributes are messed up:
[Table("Exchange")]
public partial class Exchange : BaseEntity
{
//...
[ForeignKey("Broker")]
[Required]
public int Broker_Fk { get; set; }
public virtual User Broker { get; set; }
[ForeignKey("Request")]
public int Request_Fk { get; set; }
public virtual Trade Request { get; set; }
//...
}
I'm creating an EF6 based application with Visual Studio 2013. I used the Model First approach, and after creating my data model in the editor, I can see and use the classes generated for my entities. But when following the documentation I tried to create a new instance of an entity with the static method CreateObjectName that is supposed to be autogenerated for each of the data model entities, I discovered that the autogenerated entities do not have such static methods, I can only create new instances with the new keyword. Here is the autogenerated code of one of my entities:
using System;
using System.Collections.Generic;
public partial class Movement
{
public int IdMovement { get; set; }
public MovementType Type { get; set; }
public decimal Amount { get; set; }
public Nullable<decimal> TargetAmount { get; set; }
public string Description { get; set; }
public System.DateTime Date { get; set; }
public int IdTag { get; set; }
public Nullable<int> IdContainerSource { get; set; }
public Nullable<int> IdContainerTarget { get; set; }
public virtual Tag Tag { get; set; }
public virtual Container ContainerSource { get; set; }
public virtual Container ContainerTarget { get; set; }
}
I have T4 as the Code Generation Strategy, so according to the documentation I should have those methods. I have tried regenating the code, with no luck. I think that the CreateObject static method is cleaner that using new, so I would like to get EF to autogenerate them.
Any ideas?
I'm trying to use ASP MVC 4 and Entity Framework 4 to create pretty simple web site.
I need to use the migration feature because I will deploy the application to shared hosting (GoDaddy) and I don't want to manually change tables on each change.
What is the correct way to model one-to-many relations? Using the other entity type or the other entity's primary key type?
When I use the other entity type, which is preferred because it keeps the model cleaner, the migration tools worked but the scaffolding of ASP MVC did not. Even when I've manually add drop down to select the other entity ASP MVC did not parse the request right and did not set the other entity property.
This is the two options:
Option1: Use other entity type.
public class Tenant {
[Key]
public string TenantID { get; set; }
public string Name { get; set; }
}
public class Survey {
[Key]
public string SurveyID { get; set; }
[Required]
public Tenant Tenant { get; set; }
[Required]
[StringLength(100, MinimumLength=5)]
public string Title { get; set; }
[Required]
public DateTime CreatedAt { get; set; }
}
Option 2: use primary key type.
public class Tenant {
[Key]
public string TenantID { get; set; }
public string Name { get; set; }
}
public class Survey {
[Key]
public string SurveyID { get; set; }
[Required]
public string TenantID { get; set; }
[Required]
[StringLength(100, MinimumLength=5)]
public string Title { get; set; }
[Required]
public DateTime CreatedAt { get; set; }
}
I've create MVC controller with scaffolding for the Survey entity in my ASP MVC 4 project. It create the CRUD controller and views. In the view it did not put any field for the Tenant.
After I've add it myself the method Create(Tenant tenant) was called but the Tenant field that was sent by the HTML form did not get parsed by MVC and did not set the Tenant field of the Survey entity.
Ido
These look like you are mapping one-to-one relationships and not one-to-many. If one Survey can have multiple Tenants then:
public class Tenant {
[Key]
public string TenantID { get; set; }
public string Name { get; set; }
public virtual Survey Survey {get; set;}
}
public class Survey {
[Key]
public string SurveyID { get; set; }
[Required]
[StringLength(100, MinimumLength=5)]
public string Title { get; set; }
[Required]
public DateTime CreatedAt { get; set; }
public virtual ICollection<Tenant> Tenant {get; set;}
}
I've found this series of posts which explain how to make EF models so that they will work with both EF and ASP MVC.
The idea is to have both "plain" reference type and strong reference type.
public class Team
{
public int TeamId { get; set; }
// ... other Team properties go here
// Each Team has an optional "next opponent" which is another Team
public int? NextOpponentId { get; set; }
[ForeignKey("NextOpponentId")] public virtual Team NextOpponent { get; set; }
// Each Team also has a required Manager and Administrator, both of which are people
public int ManagerId { get; set; }
public int AdministratorId { get; set; }
[ForeignKey("ManagerId")] public virtual Person Manager { get; set; }
[ForeignKey("AdministratorId")] public virtual Person Administrator { get; set; }
}