One to one relation with EF 4.1 code first - entity-framework-4.1

My question is similar to this one :
--> Many to one configuration using EF 4.1 code first
There are some fluent API solutions on google, with overriding "OnModelCreating" method and manually setting the foreign key options. But i would prefer a solution with data annotations if it is possible. Because I'd like to use inverse properties while coding. Such as TypeA object has got a TypeB object. So TypeB object should have a ParentTypeA property. Example :
public class User : IUser
{
[Key(), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
[RegularExpression(#"[A-Za-z0-9_\-\.]{2,32}"), MinLength(2), MaxLength(32)]
[Required(AllowEmptyStrings = false)]
public string UserName { get; set; }
// other props ....
// ....
public virtual UserGallery Gallery { get; set; }
}
public class UserGallery : IUserGallery
{
[Key(), DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserGalleryId { get; set; }
// other props ....
// ....
public virtual User ParentUser { get; set; }
}

A conventions way to do this in Code First is to use the UserID as the Primary Key of the UserGallery object. This is fine if its a true one to one relationship.
public class UserGallery : IUserGallery
{
[Key]
public int UserId {get;set;}
public User User {get;set;}
etc...
}
This has worked fine for me in the past.

Related

How to create a dependency graph using composite keys in EF Core

Trying to store a composite key table which is keyed for both fields to the table it defines dependencies for.
Example case
Import files: 1..10
Dependencies 1: 2,3; 2: 4,5; 4:10
Intent is to use this key-only table for code to do code first strongly typed definitions while also being light weight, and it seemed like the most straight forward way to do it before running into problems.
Current code:
public class ImportFileDependency
{
[Key]
[ForeignKey("ImportFile")]
public int ImportFileId { get; set; }
[ForeignKey("Id")]
public ImportFile ImportFile {get; set;}
[Key]
[ForeignKey("ImportFile")]
public int ImportFileDependencyId { get; set; }
[ForeignKey("Id")]
public ICollection<ImportFile> ImportFileDependencies { get; set; }
}
public class ImportFile
{
[Key]
public int Id {get; set;}
public string Name { get; set; }
public string WorkbookTab { get; set; }
public string File { get; set; }
public ICollection<ImportFileDependency> Dependencies { get; set; }
}
...
modelBuilder
.Entity<ImportFileDependency>(e =>{
e.HasKey(ifd => new { ifd.ImportFileId, ifd.ImportFileDependencyId });
e.HasOne(ifd => ifd.ImportFile)
.WithMany(i => i.Dependencies);
});
modelBuilder
.Entity<ImportFile>()
.HasMany(i => i.Dependencies)
.WithOne()
.HasForeignKey(z => z.ImportFileId);
...
After multiple revisions of following the responses of the add-migration exception response, currently on:
There are multiple properties pointing to navigation 'ImportFile' in entity type 'ImportFileDependency'. To define composite foreign key using data annotations, use ForeignKeyAttribute on navigation.
which did not update from the most recent iteration.
I seem to have recursed into a deadend so looking for guidance
Given the time you've asked it, you probably found the answer yourself or gave up on it, but if someone else struggles with this error, this solved my issue: Entity Framework Code First - two Foreign Keys from same table
You have to define the relationship using fluent API.

Relationship Using Code first with Existing database

When defining a relationship between two types is it important to include a navigation property on both types, such as in the following example:
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public Category Category { get; set; }
}
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public ICollection<Product> Products { get; set; }
}
Can I do without including the navigation property in Category ?
If you just want it infered by code first convention then yes you need both on either side. I'd also make the collection "virtual" to support lazy loading.
You can set it up using the fluent configuration when the model is built. It would be something like this
modelBuilder.Entity<Product>()
.HasMany(x => x.Category)

How can I populate a FK field using EF Code First?

I have a class Mailout with a Status that looks like this:
public class Mailout
{
public int Id {get; set; }
public string Name {get; set; }
public MailoutStatus Status { get; set; }
}
public class MailoutStatus
{
public int Id { get; set; }
public string Name { get; set;}
}
When I insert Mailouts and set the Status property, they are inserted correctly. When I fetch them, Status is always null. Since I don't have (and don't want) the status ID on my Mailout class, I have no way to retrieve it after-the-fact. How do I tell EF to populate this field eagerly, rather than lazily?
I'm hoping I can set something up in OnModelCreating() since I want this behavior all the time, not as an option that I can use sometimes by manipulating my LINQ-to-Entities queries.
You need to make your navigation properties virtual.
There is no such option in the ModelBuilder to configure an automatic eager loading of navigation properties in each query. You have to specify it query by query. As a workaround you could encapsulate eager loading in some method or property, for instance in the context:
public class MyContext : DbContext
{
public DbSet<Mailout> Mailouts { get; set; }
public IQueryable<Mailout> MailoutsWithStatus
{
get { return Mailouts.Include(m => m.Status); }
}
// ...
}
And then use in your queries:
context.MailoutsWithStatus.Where(...) ... etc.
Only an idea, it's untested.
Taking from Employee Info Starter Kit - upcoming MVC edition, here is a snippet, that works pretty well, to eager load objects when used:
public class Employee
{
...
public int? ReportsTo { get; set; }
[ForeignKey("ReportsTo")]
public virtual Employee Supervisor { get; set; }
/// <summary>
/// Children object collection of foreign key relation
/// </summary>
public virtual List<Employee> Subordinates { get; set; }
}

OpenRasta Json returning nested classes

Is it possible to return nested classes in json with OpenRasta?
I'm using EF4.1 with code first (which in theory shouldn't make a difference, as they are just POCO classes).
Here is an example:
public class AppUser
{
[Key]
public int AppUserId { get; set; }
public string WinLogin { get; set; }
public string ScreenName { get; set; }
public string AgencyId { get; set; }
public virtual ICollection<UserAppVersion> UserAppVersion { get; set; }
}
public class UserAppVersion
{
[Key]
public int UaVersionId { get; set; }
public int AppUserId { get; set; }
public int AppVersionId { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateUpdated { get; set; }
public virtual AppUser User { get; set; }
public virtual AppVersion Version { get; set; }
}
I try and return an AppUser record in json using this:
ResourceSpace.Has.ResourcesOfType<AppUser>()
.AtUri("/user").HandledBy<UserHandler>().AsJsonDataContract();
But I get an error:
System.Runtime.Serialization.SerializationException: Type 'System.Data.Entity.DynamicProxies.UserAppVersion_FD8D86F0A3AE39A0C370918637C1A90AD8D3ACA3E149677EA82C0A8D10ED0F8D' with data contract name 'UserAppVersion_FD8D86F0A3AE39A0C370918637C1A90AD8D3ACA3E149677EA82C0A8D10ED0F8D:http://schemas.datacontract.org/2004/07/System.Data.Entity.DynamicProxies' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
Unfortunately I don't know how to resolve this. Any suggestions?
That's a data contract issue, not an openrast one.
The DataContract serialzier is seeing a dynamic proxy probably generated by EF code first, and when seeing that cannot render the object.
I'd recommend either swapping for another serialziation codec, or disabling transparent lazy loading, or alternatively marking your property as an ignore for serialziation and have another property typed to a List so the serializer can function.
See DataContractSerializer Error using Entity Framework 4.0 with WCF 4.0

EF 4 Code First and M2M2M

Using Entity Framework 4 and code first how would I create a model that supports this scenario:
In an application, there are users, each user belongs to one or more groups and for each group the user can have one or more roles.
Example:
I would like to be able to say, "give me Lisa", and the response returns a user object for lisa, with the groups she belongs to. For each group there is a list property with all the roles she has for that particular group
Can anyone help me model this using code first, any help/code samples, would be great!
/Best regards Vinblad
Edit: Here is new model for your requirement.
public class User
{
public virtual int Id { get; set; }
public virtual ICollection<UserPermission> Permissions { get; set; }
}
// Permission is extended junction table to model M:N between
// User and Group but in addition it contains relation to Roles.
// The ony disadvantage is that this model doesn't control that
// role in the collection is also the role related to group. You
// must either enforce it in application logic or create some additional
// database construct to check it.
public class UserPermission
{
public virtual int UserId { get; set; }
public virtual int GroupId { get; set; }
public virtual Group Group { get; set; }
public virtual ICollection<Role> Roles { get; set; }
}
public class Group
{
public virtual int Id { get; set; }
public virtual ICollection<UserPermission> UserPermissions { get; set; }
public virtual ICollection<Role> Roles { get; set; }
}
public class Role
{
public virtual int Id { get; set; }
public virtual ICollection<Group> Groups { get; set; }
public virtual ICollection<UserPermission> UserPermissions { get; set; }
}
public class Context : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Group> Groups { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<UserPermission> UserPermissions { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Permission has composite key
modelBuilder.Entity<UserPermission>()
.HasKey(p => new {p.UserId, p.GroupId});
// Permission doesn't have navigation property to user
modelBuilder.Entity<User>()
.HasMany(u => u.Permissions)
.WithRequired()
.HasForeignKey(p => p.UserId);
modelBuilder.Entity<Group>()
.HasMany(g => g.UserPermissions)
.WithRequired(p => p.Group)
.HasForeignKey(p => p.GroupId);
}
}
As described in code there is small disadvantage. You can avoid the disadvantage by enforcing data integrity in DB by additional FK which can't be modeled by code first. You can use custom initializer to add that FK:
public class CustomInitializer : DropCreateDatabaseIfModelChanges<Context>
{
protected override void Seed(Context context)
{
context.Database.ExecuteSqlCommand(
#"ALTER TABLE [dbo].[RoleUserPermissions]
WITH CHECK ADD CONSTRAINT [FK_RoleUserPermissions_RoleGroups]
FOREIGN KEY([Role_Id], [UserPermission_GroupId])
REFERENCES [dbo].[RoleGroups] ([Role_Id], [Group_Id])");
}
}
Just add this to your application initialization (only for debug - application should not be able to drop its database in release):
Database.SetInitializer(new CustomInitializer());