Entity framework 4.1 relation to table itselft - entity-framework-4.1

is there anyone who could tell me how can i do the corresponding table mapping with entity framework code first.
Here is my table
enter link description here
i've tried to do this but without any success.
[Table("Matiere")]
public class Matiere
{
[Key]
public Int32 Id { get; set; }
public Int32? IdParent { get; set; }
[Column("NomMatiere")]
public String Nom { get; set; }
public virtual Matiere Parent { get; set; }
public virtual ICollection<Matiere> Childs { get; set; }
}
public class MatiereConfiguration : EntityTypeConfiguration<Matiere>
{
public MatiereConfiguration()
{
this.HasOptional(m => m.Parent).WithMany(m => m.Childs).HasForeignKey(m => m.IdParent);
this.HasOptional(m => m.Childs).WithRequired();
}
}
thanks in advance.

You're close. I do not think you need to supply the HasOptional(m => m.Childs).WithRequired();
First, I would put all of your mapping information into your MatiereConfiguration instead of using a mix of DataAnnotations and Fluent mappings. It's not required, but just a suggestion.
This should work:
public class MatiereConfiguration : EntityTypeConfiguration<Matiere>
{
public MatiereConfiguration()
{
HasKey(m => m.Id);
Property(m => m.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(m => m.Nom).HasColumnName("NomMatiere")
HasOptional(m => m.Parent).WithMany(m => m.Childs).HasForeignKey(m => m.IdParent);
}
}

Related

nPoco V3 - many to many not working

I have users which have many roles
public class User
{
public int Id {get;set;}
public string Name {get;set;}
public List<Role> Roles {get;set;}
}
public class Roles
{
public int Id {get;set;}
public string Key{get;set;}
}
public class UserRoles
{
public int UserId {get;set;}
public int RoleId {get;set;}
}
what I try to achieve is getting a user with all its roles in one query, but so far I failed.
For Mapping I use a custom Conventionbased mapper (I can provide the code, but it's rather big)
I tried FetchOneToMany and I tried Fetch as described here
https://github.com/schotime/NPoco/wiki/One-to-Many-Query-Helpers
https://github.com/schotime/NPoco/wiki/Version-3
But Roles is always empty.
Role and User by itself are mapped correctly and I did try to specify the relation like
For<User>().Columns(x =>
{
x.Many(c => c.Roles);
x.Column(c => c.Roles).ComplexMapping();
}, true);
Again it didn't help, roles is empty.
I have no idea what I'm missing.
Any ideas?
ComplexMapping and relationship mapping(1-to-n, n-to-n) are two different things.
ComplexMapping is for mapping nested objects for data that usually resides in the same table where there is a one-to-one relationship. For something like this:
public class Client
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Address Address { get; set; }
public Client()
{
Address = new Address();
}
}
public class Address
{
public string Street { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public string Telephone { get; set; }
public string Country{ get; set; }
}
If you're using a convention-based mapper your override would look something like this:
For<Client>().Columns(x =>
{
x.Column(y => y.Address).ComplexMapping();
});
One thing to watch for when using a convention-based mapper; you have to enable ComplexMapping in your scanner with the following code:
scanner.Columns.ComplexPropertiesWhere(y => ColumnInfo.FromMemberInfo(y).ComplexMapping);
Otherwise ComplexMapping() calls in your overrides will simply be ignored.
One-to-Many mapping would work like this (see NPoco on Github for more):
For<One>()
.TableName("Ones")
.PrimaryKey(x => x.OneId)
.Columns(x =>
{
x.Column(y => y.OneId);
x.Column(y => y.Name);
x.Many(y => y.Items).WithName("OneId").Reference(y => y.OneId);
}, true);
For<Many>()
.TableName("Manys")
.PrimaryKey(x => x.ManyId)
.Columns(x =>
{
x.Column(y => y.ManyId);
x.Column(y => y.Value);
x.Column(y => y.Currency);
x.Column(y => y.OneId);
x.Column(y => y.One).WithName("OneId").Reference(y => y.OneId, ReferenceType.OneToOne);
}, true);

Entity Framewrok 5 fluent mapping for many to many with 3 entities

I have the following scenario that is giving me a hard time:
public class SegUser
{
public string IdUser { get; set; }
public List<SegRol> SegRoles { get; set; }
public virtual List<SegApps> Apps{ get; set; }
}
public class SegRole
{
public virtual int IdRole { get; set; }
public virtual List<SegUer> SegUsers { get; set; }
public virtual List<SegApp> Apps { get; set; }
}
public class SegApp
{
public virtual int IdApp{ get; set; }
public virtual List<SegUser> Users { get; set; }
public virtual List<SegRole> Roles { get; set; }
}
In my database I have those 3 tables and an extra table with 3 PKs (one for each entity) to establish the relationship between those 3 entities.
How can I achieve the mapping with Entity Framework 5 fluent API.
I've already tried:
private void MapSegUser()
{
//mapping of another fields
entityConfiguration
.HasMany(x => x.SegRoles)
.WithMany(x => x.SegUsers)
.Map(mc =>
{
mc.MapLeftKey("id_role");
mc.MapRightKey("id_user");
mc.ToTable("seg_users_roles");
});
entityConfiguration
.HasMany(x => x.Apps)
.WithMany(x => x.Users)
.Map(mc =>
{
mc.MapLeftKey("id_app");
mc.MapRightKey("id_user");
mc.ToTable("seg_users_roles_apps");
});
}
private void MapSegApp()
{
//mapping of another fields
entityConfiguration
.HasMany(x => x.Users)
.WithMany(x => x.Apps)
.Map(mc =>
{
mc.MapLeftKey("id_user");
mc.MapRightKey("id_app");
mc.ToTable("seg_users_roles_apps");
});
}
private void MapSegRole()
{
//mapping of another fields
entityConfiguration
.HasMany(x => x.SegUsers)
.WithMany(x => x.SegRoles)
.Map(mc =>
{
mc.MapLeftKey("id_user");
mc.MapRightKey("id_role");
mc.ToTable("seg_users_roles");
});
}

Issues creating inheritance with fluent NHibernate

I trying to create inheritance so I can have some super classes with general properties and then more specialized classes that are the ones getting used.
I want something like the Table per type or table per class they make here http://www.codeproject.com/Articles/232034/Inheritance-mapping-strategies-in-Fluent-Nhibernat
So I have my supertype Game here
public abstract class Game
{
public virtual int Id { get; set; }
public virtual List<UserGame> UserList { get; set; }
}
public class GameMap : ClassMap<Game>
{
public GameMap()
{
Id(x => x.Id, "GameId")
.GeneratedBy
.HiLo("100");
HasMany(x => x.UserList)
.Cascade.All();
}
}
And then my specialized class here QMGameActive
public class QMGameActive : Game
{
public virtual DateTime LastUpdate { get; set; }
public virtual string SelectedBrick { get; set; }
public virtual int Score { get; set; }
public virtual string History { get; set; }
public virtual int StartingPlayerId { get; set; }
public QMGameActive()
{
LastUpdate = DateTime.Now;
History = "";
SelectedBrick = "";
}
}
public class QMGameActiveMap : SubclassMap<QMGameActive>
{
public QMGameActiveMap()
{
KeyColumn("GameId");
Map(x => x.LastUpdate);
Map(x => x.SelectedBrick);
Map(x => x.Score);
Map(x => x.History);
Map(x => x.StartingPlayerId);
}
}
But when I get a diagram from the server I can see there is no connection between Game and QMGameActive there
So what am I missing to make it use inheritance?
I am fairly sure that if you KeyColumn("GameId"); from the QMGameActiveMap() then NHibernate will generate QMGameActive with an ID Column of GameID which will be a foreign key of Game.GameId. which would seem to give you what you want.
(sorry away from home and cannot try code out to make sure).

unidirectional many-to-many relationship with Code First Entity Framework

I am new to EF, and trying to get many-to-many unidirectional relationship with code first approach. For example, if I have following two classes (not my real model) with be a N * N relationship between them, but no navigation property from "Customer" side.
public class User {
public int UserId { get; set; }
public string Email { get; set; }
public ICollection TaggedCustomers { get; set; }
}
public class Customer {
public int CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
The mapping code looks like ...
modelBuilder.Entity()
.HasMany(r => r.TaggedCustomers)
.WithMany(c => c.ANavgiationPropertyWhichIDontWant)
.Map(m =>
{
m.MapLeftKey("UserId");
m.MapRightKey("CustomerId");
m.ToTable("BridgeTableForCustomerAndUser");
});
This syntax force me to have "WithMany" for "Customer" entity.
The following url, says "By convention, Code First always interprets a unidirectional relationship as one-to-many."
Is it possible to override it, or should I use any other approach?
Use this:
public class User {
public int UserId { get; set; }
public string Email { get; set; }
// You must use generic collection
public virtual ICollection<Customer> TaggedCustomers { get; set; }
}
public class Customer {
public int CustomerId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
And map it with:
modelBuilder.Entity<User>()
.HasMany(r => r.TaggedCustomers)
.WithMany() // No navigation property here
.Map(m =>
{
m.MapLeftKey("UserId");
m.MapRightKey("CustomerId");
m.ToTable("BridgeTableForCustomerAndUser");
});

How do I get around this cyclical reference in EF?

I am using Entity Framework Code First with SQLCE in MVC3 for a blog-like site.
I am open to redesigning the structure if required, it would be great to get some help.
The context is set up as:
public class BinarContext : DbContext
{
public DbSet<Member> Members { get; set; }
public DbSet<Post> Posts { get; set; }
public DbSet<Reply> Replies { get; set; }
public BinarContext()
{
this.Configuration.LazyLoadingEnabled = true;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Member>().HasMany(member => member.Posts)
.WithRequired(post => post.Member)
.HasForeignKey(post => post.MemberID)
.WillCascadeOnDelete();
modelBuilder.Entity<Member>().HasMany(member => member.Replies)
.WithRequired(reply => reply.Member)
.HasForeignKey(reply => reply.MemberID)
.WillCascadeOnDelete();
modelBuilder.Entity<Post>().HasMany(post => post.Replies)
.WithRequired(reply => reply.Post)
.HasForeignKey(reply => reply.PostID)
.WillCascadeOnDelete();
base.OnModelCreating(modelBuilder);
}
}
*Note: * I have tried getting rid of WillCascadeOnDelete(); as suggested by others on SO but hasn't worked so far.
The models are:
The Member class has information about the posts and replies made by the member.
public class Member
{
public Guid ID {get; set;}
public string Username { get; set; }
public string Email { get; set; }
public virtual ICollection<Post> Posts { get; set; }
public virtual ICollection<Reply> Replies { get; set; }
}
The Post class that has information about the member who posted it and for the replied posted for it.
public class Post
{
public Guid ID {get; set;}
[DataType(DataType.MultilineText)]
public string Text { get; set; }
public Guid MemberID { get; set; }
public virtual Member Member { get; set; }
public virtual ICollection<Reply> Replies { get; set; }
}
The Reply class that has information about the member who posted it and for the post it was posted.
public class Reply
{
public Guid ID { get; set; }
[DataType(DataType.MultilineText)]
public string Text { get; set; }
public Guid PostID { get; set; }
public Guid MemberID { get; set; }
public virtual Post Post { get; set; }
public virtual Member Member { get; set; }
}
Thanks for your help :)
Try this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Member>().HasKey(x=>x.ID)
.HasMany(x => x.Posts)
.WillCascadeOnDelete();
modelBuilder.Entity<Member>().HasKey(x=>x.ID)
.HasMany(x => x.Replies)
.WillCascadeOnDelete();
modelBuilder.Entity<Post>().HasKey(x=>x.ID)
.HasMany(x => x.Replies)
.WillCascadeOnDelete();
modelBuilder.Entity<Post>().HasKey(x=>x.ID)
.WithRequired(x => x.Member)
.WithMany(x=>x.Posts);
modelBuilder.Entity<Replies>().HasKey(x=>x.ID)
.WithRequired(x => x.Member)
.WithMany(x=>x.Replies);
modelBuilder.Entity<Replies>().HasKey(x=>x.ID)
.WithRequired(x => x.Post)
.WithMany(x=>x.Replies);
base.OnModelCreating(modelBuilder);
}