EF 5 Code First using Inheritence in the class - entity-framework

I am getting Error when trying to run this code.
Unable to determine the principal end of an association between the
types 'AddressBook.DAL.Models.User' and 'AddressBook.DAL.Models.User'.
The principal end of this association must be explicitly configured
using either the relationship fluent API or data annotations.
The objective is that i am creating baseClass that has commonfield for all the tables.
IF i don't use base class everything works fine.
namespace AddressBook.DAL.Models
{
public class BaseTable
{
[Required]
public DateTime DateCreated { get; set; }
[Required]
public DateTime DateLastUpdatedOn { get; set; }
[Required]
public virtual int CreatedByUserId { get; set; }
[ForeignKey("CreatedByUserId")]
public virtual User CreatedByUser { get; set; }
[Required]
public virtual int UpdatedByUserId { get; set; }
[ForeignKey("UpdatedByUserId")]
public virtual User UpdatedByUser { get; set; }
[Required]
public RowStatus RowStatus { get; set; }
}
public enum RowStatus
{
NewlyCreated,
Modified,
Deleted
}
}
namespace AddressBook.DAL.Models
{
public class User : BaseTable
{
[Key]
public int UserID { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public string Password { get; set; }
}
}

You need to provide mapping information to EF. The following article describes code-first strategies for different EF entity inheritance models (table-per-type, table-per-hierarchy, etc.). Not all the scenarios are directly what you are doing here, but pay attention to the mapping code because that's what you need to consider (and it's good info in case you want to use inheritance for other scenarios). Note that inheritance does have limitations and costs when it comes to ORMs, particularly with polymorphic associations (which makes the TPC scenario somewhat difficult to manage). http://weblogs.asp.net/manavi/archive/2010/12/24/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-1-table-per-hierarchy-tph.aspx
The other way EF can handle this kind of scenario is by aggregating a complex type into a "fake" compositional relationship. In other words, even though your audit fields are part of some transactional entity table, you can split them out into a common complex type which can be associated to any other entity that contains those same fields. The difference here is that you'd actually be encapsulting those fields into another type. So for example, if you moved your audit fields into an "Audit" complext type, you would have something like:
User.Audit.DateCreated
instead of
User.DateCreated
In any case, you still need to provide the appropriate mapping information.
This article here explains how to do this: http://weblogs.asp.net/manavi/archive/2010/12/11/entity-association-mapping-with-code-first-part-1-one-to-one-associations.aspx

Related

Adding non-Identity tables to Identity server in ASP.NET core 2 ; do I need a different dbcontext?

I have looked and havent seen anything on this, most information relates to directly extending Identity tables.
I have extended Application User like so:
public class ApplicationUser : IdentityUser<long>
{
//[Key()]
//public long Id { get; set; }
[Required()]
[MaxLength(100)]
public string Password { get; set; }
[Required()]
[MaxLength(100)]
override public string UserName { get; set; }
[Required()]
[MaxLength(50)]
public string FirstName { get; set; }
[Required()]
[MaxLength(50)]
public string LastName { get; set; }
public virtual Organization Organization { get; set; }
}
public class ApplicationRole : IdentityRole<long>
{
}
along with other neccesary changes to ApplicationDbContext (to change the primary key to long). Other than that, its fairly standard Identity stuff. I add migrations, update; the usual tables are created plus Organization table because it's a navigation property. Organization itself has no navigation properties. Keep in mind, for the most part I was handed these classes as part of a project and am trying to work within the confines of what I've been given.
Now, I have several classes that I need to add, one as an example:
public class Event
{
[Key()]
public long Id { get; set; }
[Required()]
[MaxLength(200)]
public string Name { get; set; }
[Index]
public virtual Organization Organization { get; set; }
}
There are a handful of other something inter related classes. So in a standard code first core 2 app with no existing db, I would create the context class that derives from DbContext, whereas in Identity ApplicationDbContext (the default name) derives from IdentityDbContext.
So before I start breaking things, are there any concerns or special considerations before I do something like this?
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
public DbSet<Event> Events{ get; set; }
public DbSet<OtherClass> OtherClasses{ get; set; }
}
Note: I did find this post which seems to do what I am talking about but it is for MVC 5
You can just add the classes as properties, i.e. public DbContext<Class> Classes {get;set;} to the ApplicationDbContext class and you will get data access. They don't need to be related. If you need a sample let me know. Hope this helps.

EF5, Inherited FK and cardinality

I have this class structure:
public class Activity
{
[Key]
public long ActivityId { get; set; }
public string ActivityName { get; set; }
public virtual HashSet<ActivityLogMessage> ActivityLogMessages { get; set; }
public virtual HashSet<FileImportLogMessage> FileImportLogMessages { get; set; }
public virtual HashSet<RowImportLogMessage> RowImportLogMessages { get; set; }
}
public abstract class LogMessage
{
[Required]
public string Message { get; set; }
public DateTimeOffset CreateDate { get; set; }
[Required]
public long ActivityId { get; set; }
public virtual Activity Activity { get; set; }
}
public class ActivityLogMessage : LogMessage
{
public long ActivityLogMessageId { get; set; }
}
public class FileImportLogMessage : ActivityLogMessage
{
public long? StageFileId { get; set; }
}
public class RowImportLogMessage : FileImportLogMessage
{
public long? StageFileRowId { get; set; }
}
Which gives me this, model
Each Message (Activity, File or Row) must have be associated with an Activity. Why does the 2nd and 3rd level not have the same cardinality as ActivityLogMessage ? My attempts at describing the foreign key relationship (fluent via modelbuilder) have also failed.
This is really an academic exercise for me to really understand how EF is mapping to relational, and this confuses me.
Regards,
Richard
EF infers a pair of navigation properties Activity.ActivityLogMessages and ActivityLogMessage.Activity with a foreign key property ActivityLogMessage.ActivityId which is not nullable, hence the relationships is defined as required.
The other two relationships are infered from the collections Activity.FileImportLogMessages and Activity.RowImportLogMessages. They neither have an inverse navigation property on the other side nor a foreign key property which will - by default - lead to optional relationships.
You possibly expect that LogMessage.Activity and LogMessage.ActivityId is used as inverse property for all three collections. But it does not work this way. EF cannot use the same navigation property in multiple relationships. Also your current model means that RowImportLogMessage for example has three relationships to Activity, not only one.
I believe you would be closer to what you want if you remove the collections:
public virtual HashSet<FileImportLogMessage> FileImportLogMessages { get; set; }
public virtual HashSet<RowImportLogMessage> RowImportLogMessages { get; set; }
You can still filter the remaining ActivityLogMessages by the derived types (for example in not mapped properties that have only a getter):
var fileImportLogMessages = ActivityLogMessages.OfType<FileImportLogMessage>();
// fileImportLogMessages will also contain entities of type RowImportLogMessage
var rowImportLogMessage = ActivityLogMessages.OfType<RowImportLogMessage>();

Entity framework two-way relationship not loading includes

This is making me feel like an idiot. Entity Framework is supposed to be fairly simple, yet I can't sort this out myself and clearly I've got a fundamental misunderstanding. I hope it doesn't turn out to be an idiot-question - sorry if it is.
Three code-first objects, related to one another.
public class Schedule
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid RowId { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
public virtual ICollection<Charge> Charges { get; set; }
}
public class Charge
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid RowId { get; set; }
public decimal Rate { get; set; }
public Type Type { get; set; }
}
public class Type
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid RowId { get; set; }
public string TypeName { get; set; }
}
When I query this, I want all related types, so:
Schedule currentSchedule = _Context.Schedules
.Include("Charges.Type")
.Where(cs => cs.Start < dateWindow && cs.End > dateWindow)
.First();
In C#, this has been working fine.
The problem arises because we're not stopping at C#, but passing the data onto a javascript library called Breeze with smooths out data operations at the client end. Breeze has a bug/feature which demands that EF relationships between objects be specified at BOTH ENDS. So when I do my query above, I don't end up with any Types, because their relationship with Charge isn't directly specified.
So I change it to this:
public class Type
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid RowId { get; set; }
public string TypeName { get; set; }
public virtual Charge Charge { get; set; }
}
Because virtual is a navigation property, so that should enable Breeze should now to go both ways across the relationship without changing the data structure. But EF doesn't like this. It tells me:
Unable to determine the principal end of an association between the
types 'Core.Charge' and 'Core.Type'. The principal end of this
association must be explicitly configured using either the
relationship fluent API or data annotations
Fair enough. I can see how this could be confusing. Now, my understanding is that if you define a foreign key in a dependent class, it has to be that classes' primary key. So we change it to:
public class Type
{
[Key, ForeignKey("Charge"), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid RowId { get; set; }
public string TypeName { get; set; }
public virtual Charge Charge { get; set; }
}
And that seems to work but ... it's stopped loading any Type information when you ask for a schedule. Messing around with the includes doesn't seem to do anything at all.
What's going on, and what have I done wrong?
You haven't only added a navigation property (Type.Charge) to an existing model/relationship. Instead you have changed the relationship completely from a one-to-many to a one-to-one relationship because by default if a relationship has only one navigation property EF assumes a one-to-many relationship. With your change you have configured a one-to-one relationship.
Those relationships have different foreign keys: The original one-to-many relationship has a separate foreign key in the Charge table (probably named Type_RowId or similar). Your new relationship has the foreign key at the other side in table Type and it is the primary key RowId. The Charges you are loading together with the Schedule probably don't have any related Type with the same primary key, hence no Type is loaded.
If you actually want to reproduce the old (one-to-many) relationship with just a navigation property at the other side you must add a collection to Type instead of a single reference:
public class Type
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid RowId { get; set; }
public string TypeName { get; set; }
public virtual ICollection<Charge> Charges { get; set; }
}
Are you sure that you want to put ForeignKey on RowId, I think you may want to define some relationship like this
public class Type
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid RowId { get; set; }
public string TypeName { get; set; }
public int ChargeId { get; set; }
[ForeignKey("ChargeId")]
public virtual Charge Charge { get; set; }
}

Database Generated by EF5 Not Creating Join Table When There are Multiple Relationships

I have a User and an Organization class. They look like this
public class User
{
public int UserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Organization> Organizations { get; set; }
}
public class Organization : EntityBase
{
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<User> Users { get; set; }
}
And both inherit from an EntityBase class to get common fields like Id and created/updated tracking.
public abstract class EntityBase
{
public int Id { get; set; }
public DateTime Created { get; set; }
public virtual User CreatedBy { get; set; }
public DateTime Updated { get; set; }
public virtual User UpdatedBy { get; set; }
}
As denoted by the ICollection properties on both, there should be a many-to-many relation. However when my database is autogenerated I get incorrect foreign keys added to my tables
If I change the CreatedBy and UpdatedBy to be strings instead of User properties I get a join table, which is what I was looking for.
Is this a matter of Entity Framework simply being confused and I need to supply many-to-many configuration in the using fluent mappings, or have I done something wrong?
If you have multiple relationships you need to configure them manually by fluent API or using attributes,
Note:If you have multiple relationships between the same types (for
example, suppose you define the Person and Book classes, where the
Person class contains the ReviewedBooks and AuthoredBooks navigation
properties and the Book class contains the Author and Reviewer
navigation properties) you need to manually configure the
relationships by using Data Annotations or the fluent API
Here is the article from Microsoft.

EF CTP4: For Code Only, no database generation needed, how much DB info is needed?

I have a database, and I have entity POCO's, and all I want to use EF for is to map between the two and keep track of changes for loading, saving, etc.
I have been reading a lot of the literature (such as it is) on "Code First", and I am unclear on how much of the database information I need to supply when there is not going to be a database generated.
For example, does EF need to know which properties are keys, the maximum length of string properties, the relationships between the tables, etc.? Or if it does need to know, can it get that information from the database itself? In other words, do I have to provide [Key] annotations and such, or provide configuration information detailing the foreign-key relationships, if no database needs to be created?
UPDATE: To make things a little clearer, the following code is what I am talking about. I have to manually create this class derived from DbContext. I could supply a lot of DB information about the properties in OnModelCreating, or in attributes attached to the properties in the entity classes.
public class SchedulerContext : DbContext
{
public SchedulerContext(EntityConnection connection)
: base(connection)
{
}
public DbSet<Client> Clients { get; set; }
public DbSet<ConsultantDistrict> ConsultantDistricts { get; set; }
public DbSet<ConsultantInterviewSetting> ConsultantInterviewSettings { get; set; }
public DbSet<ConsultantUnavailable> ConsultantsUnavailable { get; set; }
public DbSet<CustomEmailTemplate> CustomEmailTemplates { get; set; }
public DbSet<DateEvent> DateEvents { get; set; }
public DbSet<Event> Events { get; set; }
public DbSet<EventItem> EventItems { get; set; }
public DbSet<EventItemUserViewed> EventItemsUserViewed { get; set; }
public DbSet<FlaggedDate> FlaggedDates { get; set; }
public DbSet<Interview> Interviews { get; set; }
public DbSet<Interviewee> Interviewees { get; set; }
public DbSet<IntervieweeNote> IntervieweeNotes { get; set; }
public DbSet<InterviewEvent> InterviewEvents { get; set; }
public DbSet<NotificationSent> NotificationsSent { get; set; }
public DbSet<SchedulerRole> SchedulerRoles { get; set; }
public DbSet<SiteEvent> SiteEvents { get; set; }
public DbSet<UnavailableHour> UnavailableHours { get; set; }
public DbSet<UserLogin> UserLogins { get; set; }
public DbSet<UserSites> UserSites { get; set; }
public DbSet<Visit> Visits { get; set; }
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ConsultantUnavailable>().MapSingleType().ToTable("ConsultantsUnavailable");
modelBuilder.Entity<EventItemUserViewed>().MapSingleType().ToTable("EventItemsUserViewed");
}
}
Yes, the EF does need information on string field lengths, foreign keys, etc., in the model. For example, if a DB FK has a cascade, the EF needs to know that so that it doesn't force you to manually delete detail records; if the EF is aware of the cascade it will let the DB handle that. Similarly, if the EF is aware that a key is store-generated (e.g., auto-incremented), it won't complain when you don't set it on a new record, because it will presume that the DB will do that.
However, the code-only approach takes a "convention over configuration" approach. You don't have to specify values which the EF can guess. You can read about those here.
If you are doing Code Only, the EF doesn't look at the DB at all when creating the model.
There is no way to tell the EF to look at code and the DB to create the model. You have to choose one or the other.