CreateObjectName static method not being autogenerated by EF tools - entity-framework

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?

Related

MVC5 Models outside of area EF6

I am trying to call a public virtual into a Asset.cs to link data on the ModelID.
My issue is that the Model.cs is outside of the area of where the asset.cs is.
How do i link the two tables models together when they are separated by areas ?
Assets.cs in a area, using "model" is an issue in the public virtual because it cant find it in the Area.
namespace Assets.Areas.Company.Models
{
public class Asset
{
[Key]
public int AssetID { get; set; }
public int ModelID { get; set; }
public virtual Model ModelName { get; set; }
Model.cs outside the area
namespace Assets.Models
{
public class Model
{
[Key]
public int ModelID { get; set; }
public int AssetAssignmentID { get; set; }
[Required]
[StringLength(100, MinimumLength = 2)]
public string ModelName { get; set; }
I have tried a viewmodel approach but it just adds the fields to the asset table rather than foreign keys when i use public virtual ModelVM ModelName { get; set; }
I have tried using the using Assets.Models; to link to the model.cs when looking at public virtual Model ModelName { get; set; } , but when updating the table an object named 'models' is already in the database.
I have found i can you models outside of an area, with:
using Assets.Models;
My EF Migration was causing me the issue with "object named 'models' is already in the database." This was because the table Models was already there!

Entity Framework Core not loading related data

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; }
//...
}

EF Code-First creates some fields ,even I added ForeignKey annotations

can any one help me in this ?
Here is my 2 classes
class Request
{
public Nullable<int> BuyCurrencyId {get ; set;}
public Nullable<int> SaleCurrencyId {get ; set;}
[ForeignKey("SaleCurrencyId")]
public virtual Currency SaleCurrency { get; set; }
[ForeignKey("BuyCurrencyId")]
public virtual Currency BuyCurrency { get; set; }
}
class Currency
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Request> Requests { get; set; }
public virtual ICollection<Request> Requests1 { get; set; }
}
I checked the updated with EF database , and I found out that the EF create Reqyests table like this :
SaleCurrencyId int (Already exists)
BuyCurrencyId int (Already exists)
Currency_Id int (Added by EF)
Currency_Id1 int (Added by EF)
By this not thing I expect. I thing the last tow columns are not correct and they not be exist.
Can any one help me ?
I am using EF 6 alpha to update the existing database with my generated model by T4.Please keep it in mind that I want to use data annotations , not Fluent API
Sorry about my bad English
Update 1 :
I thought if I change the Currency class to this it will resolve my problem , but it did not.
class Currency
{
public int Id { get; set; }
public string Name { get; set; }
[InverseProperty("SaleCurrencyId")]
public virtual ICollection<Request> Requests { get; set; }
[InverseProperty("BuyCurrencyId")]
public virtual ICollection<Request> Requests1 { get; set; }
}
Your Update1 is almost the correct solution, but the parameter of the [InverseProperty] attribute must be the navigation property in Request, not the foreign key property:
[InverseProperty("SaleCurrency")]
public virtual ICollection<Request> Requests { get; set; }
[InverseProperty("BuyCurrency")]
public virtual ICollection<Request> Requests1 { get; set; }

breeze.js one to many

I'm currently building an SPA with Web API and knockout etc. So far i worte my own simple datacontext and it worked pretty well.
The I bumped in to breeze and thought it might be worth a try. especially I hoped to get a simpler approach on navigation between the entities...
to load a entities or a single entity with breeze worked fine. Working with navigation properties seems not to work. The navigation property is always empty, even though it's a one to many relationship.
Here is my model (simplified):
public class WorkdayHours
{
public int Id { get; set; }
public bool IsWorkDay { get; set; }
...
public Byte WeekDay { get; set; }
}
public class Service
{
public int Id { get; set; }
public string DisplayName { get; set; }
public virtual ICollection<WorkdayHours> BookableDays { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string DisplayName { get; set; }
public virtual ICollection<WorkdayHours> BookableDays { get; set; }
}
public class Shop
{
public int Id { get; set; }
public string DisplayName { get; set; }
public virtual ICollection<WorkdayHours> BookableDays { get; set; }
}
Then I fetch the entity service ind my SPA as follow:
var query = EntityQuery
.from('Services')
.where('id', 'eq', serviceId)
.expand('BookableDays');
As when teh query is executed I get as result the requested service entity with all the data except the bookableDay property is always an empty array.
When I check the Json answer I see that also the workdayHours are transmitted and breeze even calls my defined ctors for this entities. However they are not linked to the bookableDays property itself.
When checking the genrated DB model, EF generated foreignkeys for service, employee and shop in workdayHours as expected.
Is breeze not capable with having several optional foreignkeys?
Suggestion and ideas highly apprechiated.
Breeze is dependent on Foreign Keys. I had a similar problem. This should solve it:
EF was generating the ForeignKeys for me too and the related Entites where still empty. As far as i know breeze needs the explicit Annotation/Configuration of ForeignKey Fields.
public class Mvl
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long MvlId{ get; set; }
public DateTime CreatedAt { get; set; }
[InverseProperty("Mvl")]
public ICollection<MvlOP> MvlOps { get; set; }
public DateTime? ReleasedAt { get; set; }
public DateTime? LockedAt { get; set; }
public DateTime? ClosedAt { get; set; }
//[ConcurrencyCheck]
//public int? RowVersion { get; set; }
[Timestamp]
public byte[] TimeStamp { get; set; }
}
public class MvlOP
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long MvlOpId { get; set; }
public long MvlId { get; set; }
[ForeignKey("MvlId")]
public Mvl Mvl { get; set; }
...
}

Entity Framework 5 code first not mapping a model

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; }