I'm using Fluent Migrator and Fluent NHibernate in the same project but when I launch queries using Database.Session.Query<ENTITY>().** some return data and some don't. I can't tell where I'm doing wrong.
Database Query That Returns Users:
var users = Database.Session.Query<Models.User>()
.Where(u => u.Id == id)
.ToList();
Database Query That Doesn't Return Users:
var ourStocks = Database.Session.Query<Models.Stock>()
.Where(stock => stock.Belongstouser == id)
.OrderByDescending(stc => stc.StockId)
.ToList();
Models.User:
public class User
{
public virtual int Id { get; set; }
public virtual string Username { get; set; }
public virtual string Email { get; set; }
public virtual string adSoyad { get; set; }
public virtual string addressMah { get; set; }
public virtual string addRessCadSk { get; set; }
public virtual string addressIl { get; set; }
public virtual string addressIlce { get; set; }
public virtual int Balance { get; set; }
public virtual string PasswordHash { get; set; }
public virtual IList<Roles> Roles { get; set; }
public User()
{
Roles = new List<Roles>();
}
public virtual void SetPassword(string password)
{
PasswordHash = BCrypt.Net.BCrypt.HashPassword(password, 13);
}
public virtual bool CheckPassword(string password)
{
var pass = BCrypt.Net.BCrypt.Verify(password, PasswordHash);
return BCrypt.Net.BCrypt.Verify(password, PasswordHash);
}
}
public class UsersMap : ClassMapping<User>
{
public UsersMap()
{
Table("users");
Schema("projefinalodevi");
Id(x => x.Id, map => map.Generator(Generators.Identity));
Property(x => x.Username, map => map.NotNullable(true));
Property(x => x.Email, map => map.NotNullable(true));
Property(x => x.adSoyad, map => map.NotNullable(true));
Property(x => x.addressMah, map => map.NotNullable(true));
Property(x => x.addRessCadSk, map => map.NotNullable(true));
Property(x => x.addressIl, map => map.NotNullable(true));
Property(x => x.addressIlce, map => map.NotNullable(true));
Property(x => x.Balance, map => map.NotNullable(true));
Property(x => x.PasswordHash, map => { map.Column("password_hash"); map.NotNullable(true); });
Bag(x => x.Roles, x => {
x.Table("role_users");
x.Key(k => k.Column("userid"));
}, x => x.ManyToMany(k => k.Column("roleid")));
}
}
Models.Stock:
public class Stock
{
public virtual int StockId { get; set; }
public virtual int Description { get; set; }
public virtual string Unitprice { get; set; }
public virtual int Belongstouser { get; set; }
public virtual int Quantityinstock { get; set; }
}
public class StockMap : ClassMapping<Stock>
{
public StockMap()
{
Table("stock");
Schema("projefinalodevi");
Lazy(true);
Id(x => x.StockId, map => { map.Column("stock_id"); map.Generator(Generators.Identity); });
Property(x => x.Description, map => map.NotNullable(true));
Property(x => x.Unitprice, map => map.NotNullable(true));
Property(x => x.Belongstouser, map => map.NotNullable(true));
Property(x => x.Quantityinstock, map => { map.Column("quantityInStock"); map.NotNullable(true); });
}
}
And lastly, my Migration:
public override void Down()
{
Execute.Sql("DELETE FROM projeFinalOdevi.roles where name = 'user'");
Execute.Sql("DELETE FROM projeFinalOdevi.roles where name = 'admin'");
Delete.Table("role_users");
Delete.Table("roles");
Delete.Table("sales");
Delete.Table("stock");
Delete.Table("users");
}
public override void Up()
{
Create.Table("users")
.WithColumn("id").AsInt32().Identity().PrimaryKey()
.WithColumn("userName").AsString(50).NotNullable()
.WithColumn("eMail").AsString(50).NotNullable()
.WithColumn("balance").AsInt32().NotNullable()
.WithColumn("adSoyad").AsString(128).NotNullable()
.WithColumn("addressMah").AsString(40).NotNullable()
.WithColumn("addressCadSk").AsString(128).NotNullable()
.WithColumn("addressil").AsString(128).NotNullable()
.WithColumn("addressilce").AsString(128).NotNullable()
.WithColumn("password_hash").AsString(256).NotNullable();
Create.Table("stock")
.WithColumn("stock_id").AsInt32().Identity().PrimaryKey()
.WithColumn("description").AsString(256).NotNullable()
.WithColumn("unitPrice").AsInt32().NotNullable()
.WithColumn("belongsToUser").AsInt32().NotNullable()
.WithColumn("quantityInStock").AsInt32().NotNullable();
Create.Table("sales")
.WithColumn("sales_id").AsInt32().Identity().PrimaryKey()
.WithColumn("stock_id").AsInt32().ForeignKey("stock", "stock_id").OnDelete(System.Data.Rule.Cascade).NotNullable()
.WithColumn("date").AsDate().NotNullable()
.WithColumn("quantity").AsInt32().NotNullable()
.WithColumn("sale_sum").AsInt32().NotNullable();
Create.Table("roles")
.WithColumn("id").AsInt32().Identity().PrimaryKey()
.WithColumn("name").AsString(128);
Create.Table("role_users")
.WithColumn("userid").AsInt32().ForeignKey("users", "id").OnDelete(System.Data.Rule.Cascade)
.WithColumn("roleid").AsInt32().ForeignKey("roles", "id").OnDelete(System.Data.Rule.Cascade);
Execute.Sql("INSERT INTO projeFinalOdevi.roles (name) VALUES ('admin')");
Execute.Sql("INSERT INTO projeFinalOdevi.roles (name) VALUES ('user')");
/* CMD line;
migrate -a D:\ProjeFinalOdevi\ProjeFinalOdevi\bin\ProjeFinalOdevi.dll -db MySql -conn "Data Source=127.0.0.1;Database=projefinalodevi;uid=root;pwd=MySQLPassis8420;"
*//* CMD line;
migrate -a C:\Users\Atabay\source\repos\ProjeFinalOdevi\ProjeFinalOdevi\bin\ProjeFinalOdevi.dll -db MySql -conn "Data Source=127.0.0.1;Database=ProjeFinalOdevinew;uid=root;pwd=root;"
*/
}
Help is appreciated, thanks :).
Turns out I was not registering the stock.
Related
I have a model class
public class Brochure
{
[Key]
public int BrochureId { get; set; }
public string Name { get; set; }
public string TypeOfCover { get; set; }
public int NumberOfPages { get; set; }
public LibraryType Type { get; set; }
}
and View model
public class BrochureView
{
public int BrochureId { get; set; }
public string Name { get; set; }
public string TypeOfCover { get; set; }
public int NumberOfPages { get; set; }
}
in Brochure service I'm mapping model and viewmodel
public class BrochureService
{
private BrochureRepository _brochureRepository;
public BrochureService(DbContextOptions<LibraryContext> options)
{
_brochureRepository = new BrochureRepository(options);
}
public void Create(BrochureView brochureView)
{
var brochure = Mapper.Map<BrochureView, Brochure>(brochureView);
brochure.Type = LibraryType.Brochures;
_brochureRepository.Create(brochure);
}
}
Here is my automapper profiler:
public static class AutoMapperProfile
{
public static void RegisterMappings()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Brochure, BrochureView>();
cfg.CreateMap<BrochureView, Brochure>()
.ForMember(src => src.Type, opt => opt.Ignore());
});
}
}
but i have an exception:
Unmapped members were found.
AutoMapper cant map "Type" property. How can I resolve this problem?
To answer question from comments, that's the whole MappingProfile
public static class AutoMapperProfile
{
public static void RegisterMappings()
{
Mapper.Initialize(cfg =>
{
cfg.CreateMap<Book, BookView>();
cfg.CreateMap<BookView, Book>();
cfg.CreateMap<Magazine, MagazineView>();
cfg.CreateMap<MagazineView, Magazine>();
cfg.CreateMap<Brochure, BrochureView>();
cfg.CreateMap<BrochureView, Brochure>()
.ForMember(src => src.Type, opt => opt.Ignore());
cfg.CreateMap<PublicHouse, PublicHouseView>();
cfg.CreateMap<PublicHouseView, PublicHouse>();
cfg.CreateMap<Book, LibraryView>()
.ForMember(dest => dest.Name, opt => opt.ResolveUsing(src => src.Name))
.ForMember(dest => dest.Type, opt => opt.ResolveUsing(src => (LibraryType)src.Type));
cfg.CreateMap<Brochure, LibraryView>()
.ForMember(dest => dest.Name, opt => opt.ResolveUsing(src => src.Name))
.ForMember(dest => dest.Type, opt => opt.ResolveUsing(src => (LibraryType)src.Type));
cfg.CreateMap<Magazine, LibraryView>()
.ForMember(dest => dest.Name, opt => opt.ResolveUsing(src => src.Name))
.ForMember(dest => dest.Type, opt => opt.ResolveUsing(src => (LibraryType)src.Type));
});
}
}
I have a project with fluent-nhibernate. And here is my models and mapping:
TapuKisiKisi.cs:
public class TapuKisiModel : SModuleClass
{
public virtual int Kod { get; set; }
public virtual long TapuKod { get; set; }
public virtual string Ad { get; set; }
public virtual TapuKisiTipModel KisiTip { get; set; }
[JsonIgnore]
public virtual IList<TapuHisseBilgisiModel> HisseBilgisi { get; set; }
public virtual TapuTuzelKisiModel TuzelKisi { get; set; }
public virtual TapuGercekKisiModel GercekKisi { get; set; }
public TapuKisiModel()
{
HisseBilgisi = new List<TapuHisseBilgisiModel>();
}
}
TapuKisiModelMap.cs:
public class TapuKisiModelMap : ClassMap<TapuKisiModel>
{
public TapuKisiModelMap()
{
Table("TAPU_KISI");
Id(x => x.Kod);
Map(x => x.Ad);
Map(x => x.TapuKod);
Map(x => x.Record).Length(25).Nullable();
Map(x => x.RecordDate).Nullable();
Map(x => x.Edit).Length(25);
Map(x => x.EditDate);
References(x => x.KisiTip).PropertyRef(x => x.TapuKod).Column("CinsiyetTapuKod").Index("IX_KISI_CINSIYETTAPUKOD");
References(x => x.GercekKisi).Column("GercekKisiKod").Cascade.SaveUpdate().Index("IX_KISI_GERCEKKISIKOD");
References(x => x.TuzelKisi).Column("TuzelKisiKod").Cascade.SaveUpdate().Index("IX_KISI_TUZELKISIKOD");
HasMany(x => x.HisseBilgisi).PropertyRef("TapuKod").KeyColumn("KisiTapuKod").Cascade.SaveUpdate();
}
}
TapuHisseBilgisiModel.cs:
public partial class TapuHisseBilgisiModel : SModuleClass
{
public virtual int Kod { get; set; }
public virtual long TapuKod { get; set; }
public virtual string EdinmeSebep { get; set; }
public virtual decimal HissePay { get; set; }
public virtual decimal HissePayda { get; set; }
public virtual TapuIslemModel Islem { get; set; }
}
TapuHisseBilgisiModelMap.cs:
public TapuHisseBilgisiModelMap()
{
Table("TAPU_HISSE_BILGISI");
Id(x => x.Kod);
Map(x => x.TapuKod);
Map(x => x.EdinmeSebep);
Map(x => x.HissePay);
Map(x => x.HissePayda);
Map(x => x.Record).Length(25).Nullable();
Map(x => x.RecordDate).Nullable();
Map(x => x.Edit).Length(25);
Map(x => x.EditDate);
HasOne(x => x.Islem).ForeignKey("HisseBilgisiTapuKod").PropertyRef(x => x.HisseBilgisi);
References(x => x.Kisi).PropertyRef(x => x.TapuKod).Column("KisiTapuKod").Index("IX_HISSEBILGISI_KISITAPUKOD");
References(x => x.Zemin).PropertyRef(x => x.TapuKod).Column("ZeminTapuKod").Index("IX_HISSEBILGISI_ZEMINTAPUKOD");
}
My models and mappings are like these. When i run project working normally. But when i call again same method to save database it's adding same data again. I need only update if data is exist.
And here is my source to kisi adding database:
internal bool AddKisiToDatabase(List<TapuKisiModel> kisiList)
{
using (ISession session = DatabaseProvider.SessionFactory.OpenSession())
{
using (ITransaction transaction = session.BeginTransaction())
{
try
{
foreach (var kisi in kisiList)
{
TapuKisiModel currentKisi = session
.QueryOver<TapuKisiModel>()
.Where(x => x.TapuKod == kisi.TapuKod)
.SingleOrDefault();
if (currentKisi != null)
{
currentKisi.TapuKod = kisi.TapuKod;
foreach (var hisse in kisi.HisseBilgisi)
{
currentKisi.HisseBilgisi.Add(hisse);
}
session.Update(currentKisi);
}
else
{
session.Save(kisi);
}
}
transaction.Commit();
return true;
}
catch (Exception ex)
{
SNLog.SLogger.Error(string.Format("{0} - {1}", "An Error Occurred While Adding tuzelKisiList To Database", ex.Message));
return false;
}
}
}
}
I run this code first time adding kisi to database and adding hissebilgisi too. But i run this code second time it's update kisi data in database and adding hissebilgisi again. So there will duplicated hissebilgisi in database. I don't want that. I need if need update hissebilgisi too, if there is no hissebilgisi add to database.
What should i do?
Note:I'm sorry my english is not very well i know.
it should be work
internal bool AddKisiToDatabase(List<TapuKisiModel> kisiList)
{
bool state = false;
using (ISession session = DatabaseProvider.SessionFactory.OpenSession())
{
try
{
using (ITransaction transaction = session.BeginTransaction())
{
foreach (var kisi in kisiList)
{
TapuKisiModel currentKisi = new TapuKisiModel();
currentKisi = session
.QueryOver<TapuKisiModel>()
.Where(x => x.TapuKod == kisi.TapuKod)
.SingleOrDefault();
session.SaveOrUpdate(currentKisi);
transaction.Commit();
}
}
state = true;
}
catch (Exception ex)
{
SNLog.SLogger.Error(string.Format("{0} - {1}", "An Error Occurred While Adding tuzelKisiList To Database", ex.Message));
}
}
return state;
}
I am new to using EF6 with code-first, and I don't now how to create a correct relationship in my map.
Basically I have this entity
Menu
MenuGrupo
Menu 1 x N MenuGrupo
Somenthing, like Menu 1 X n MenuItens
These are my classes:
public class Menu
{
public Menu()
{
ListaFilhos = new List<Menu>();
}
public Int32 MenuID { get; set; }
public String Nome { get; set; }
public String Action { get; set; }
public String Controller { get; set; }
public String Url { get; set; }
public Int32? Pai { get; set; }
public Boolean? Ativo { get; set; }
public virtual List<Menu> ListaFilhos { get; set; }
}
public class MenuMap : EntityTypeConfiguration<Entidade.Menu>
{
public MenuMap()
{
HasKey(x => x.MenuID);
Property(x => x.MenuID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.Pai).IsRequired();
Property(x => x.Nome).HasColumnType("varchar").HasMaxLength(100).IsRequired();
Property(x => x.Url).HasColumnType("varchar").HasMaxLength(250);
Property(x => x.Action).HasColumnType("varchar").HasMaxLength(50);
Property(x => x.Controller).HasColumnType("varchar").HasMaxLength(50);
Property(x => x.Ativo).IsRequired();
ToTable("Menu");
}
}
public class MenuGrupo
{
public MenuGrupo()
{
ListaMenu = new List<Menu>();
}
public Int32 MenuGrupoID { get; set; }
public Int32 MenuID { get; set; }
public virtual List<Menu> ListaMenu { get; set; }
}
public class MenuGrupoMap : EntityTypeConfiguration<Entidade.MenuGrupo>
{
public MenuGrupoMap()
{
HasKey(x => x.MenuGrupoID);
Property(x => x.MenuGrupoID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.MenuID).IsRequired();
ToTable("MenuGrupo");
}
}
Please have a look at Getting Started with Entity Framework 6 Code First using MVC 5. It is really very helpful and let you build your project properly.
Regarding to your situation, it would be enough to use DataAnnotations instead of Fluent API at least for starting.
Hoıpe this helps...
You're using List<Menu>, whereas you should be using ICollection<Menu>. The reason why this is necessary is pretty low-level, but suffice to say, it has to do with how Entity Framework handles relationships and things like lazy-loading. A List<T> property requires that the query be executed immediately.
I am trying to map information about the User to several dto's, but I'm getting null exceptions. Basically, the reason why I distributed the information among several classes is because there are common info that I need in several views. So this is what I ended up with:
User entity class
public class User
{
public int Id { get; set; }
public string Nickname { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public float Credits { get; set; }
public float PromotionalCredits { get; set; }
public string Telephone { get; set; }
public string Mobile { get; set; }
public double RatingAverage { get; set; }
public string ProfileImage { get; set; }
public virtual ICollection<Address> Addresses { get; set; }
public virtual ICollection<Role> Roles { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
public virtual ICollection<Item> Items { get; set; }
public virtual ICollection<Bid> Bids { get; set; }
public virtual ICollection<CreditCard> CreditCard { get; set; }
public virtual ICollection<Message> ReceivedMessages { get; set; }
public virtual ICollection<Message> SentMessages { get; set; }
public virtual ICollection<Item> WatchList { get; set; }
public virtual ICollection<Rating> OwnRatings { get; set; }
public virtual ICollection<Rating> RatingsForOthers { get; set; }
}
DTO's and ViewModel calsses
public class UserInfoSummaryViewModel
{
public int Id { get; set; }
public string FullName { get; set; }
public UserDetailedStatus DetailedStatus { get; set; }
}
public class UserDetailedStatus
{
public float TotalCredits { get; set; }
public float Credits { get; set; }
public float PromotionalCredits { get; set; }
public BiddingAndItems BiddingAndItems { get; set; }
public int OngoingListings { get; set; }
public int NewMessages { get; set; }
public float Rating { get; set; }
public int NumberOfRatings { get; set; }
}
public class BiddingAndItems
{
public int TotalBids { get; set; }
public int WinningBids { get; set; }
public int AcquiredItems { get; set; }
public int ItemsAwaitingConfirmation { get; set; }
public List<ItemForUserBids> Items { get; set; }
}
Mappings inside AutoMapperBootStrapper class
Mapper.CreateMap<User, BiddingAndItems>()
.ForMember(m => m.TotalBids, o => o.MapFrom(s => s.TotalActiveBids()))
.ForMember(m=>m.ItemsAwaitingConfirmation, o=>o.MapFrom(s=>s.Items.Count(i=>i.IsAwaitingReceptionConfirmation().Equals(true))))
.ForMember(m=>m.AcquiredItems, o=>o.MapFrom(s=>s.AquiredItems().Count))
.ForMember(m => m.WinningBids,
o => o.MapFrom(s => s.Bids.Where(c => c.Item.CurrentHighestBidderId().Equals(s.Id))));
Mapper.CreateMap<User, UserDetailedStatus>()
.ForMember(m => m.NumberOfRatings, o => o.MapFrom(s => s.OwnRatings.Count()))
.ForMember(m => m.NewMessages, o => o.MapFrom(s => s.TotalUnreadMessages()))
.ForMember(m => m.OngoingListings, o => o.MapFrom(s => s.Items.Where(i => i.IsPublished())))
.ForMember(m => m.Rating, o => o.MapFrom(s => s.RatingAverage))
.ForMember(m => m.TotalCredits, o => o.MapFrom(s => s.TotalCredits()));
Mapper.CreateMap<User, UserInfoSummaryViewModel>();
Call to automapper inside UserController
public ActionResult Summary()
{
var user = _helper.GetUserFromSession();
var viewModel = Mapper.Map<User, UserInfoSummaryViewModel>(user);
return View(viewModel);
}
I thought because I have all the necessary mappings inside the bootstrapper this should, theoretically work, apparently I was wrong... How can I fix that?
UPDATE:
I got my mappings fixed and added a couple of value resolvers. Now I'm not getting a null reference exception but there seems to be something wrong because everytime I run the project it gets stuck and then the local server stops responding... Here's my code:
Mapper.CreateMap<User, BiddingAndItems>()
.ForMember(m => m.TotalBids, o => o.MapFrom(s => s.TotalActiveBids()))
.ForMember(m => m.ItemsAwaitingConfirmation,
o => o.MapFrom(s => s.Items.Count(i => i.IsAwaitingReceptionConfirmation().Equals(true))))
.ForMember(m => m.AcquiredItems, o => o.MapFrom(s => s.AquiredItems().Count))
.ForMember(m => m.WinningBids, o => o.ResolveUsing<WinningBidsResolver>())
.ForMember(m => m.Items, o => o.ResolveUsing<BiddingItemResolver>());
Mapper.CreateMap<User, UserDetailedStatus>()
.ForMember(m => m.NumberOfRatings, o => o.MapFrom(s => s.OwnRatings.Count()))
.ForMember(m => m.NewMessages, o => o.MapFrom(s => s.TotalUnreadMessages()))
.ForMember(m => m.OngoingListings, o => o.MapFrom(s => s.Items.Where(i => i.IsPublished()).Count()))
.ForMember(m => m.Rating, o => o.MapFrom(s => s.RatingAverage))
.ForMember(m=>m.BiddingAndItems, o => o.MapFrom(s=> s))
.ForMember(m => m.TotalCredits, o => o.MapFrom(s => s.TotalCredits()));
Mapper.CreateMap<User, UserInfoSummaryViewModel>()
.ForMember(m => m.DetailedStatus, o => o.MapFrom(s => s));
public class BiddingItemResolver : ValueResolver<User, List<ItemForUserBids>>
{
protected override List<ItemForUserBids> ResolveCore(User source)
{
var items = new List<ItemForUserBids>();
foreach (var bid in source.Bids)
{
var item = bid.Item;
var c = new ItemForUserBids
{
BidValue = bid.Amount,
Description = item.Description,
Id = item.Id,
ItemThumb = item.MainImageLink(),
Status = source.ItemBiddingStatus(item.Id),
TimeLeft = TimeUtility.TimeLeft(item.EndDate),
Title = item.Title
};
items.Add(c);
}
return items;
}
}
public class WinningBidsResolver : ValueResolver<User, int>
{
protected override int ResolveCore(User source)
{
return source.Bids.Where(c => c.Item.CurrentHighestBidderId().Equals(source.Id)).Count();
}
}
The problem is that I'm not getting any exceptions to give me any hints about what's going wrong... It just gets stuck! I suspect that my mappings are going into some sort of an infinite loops or something, but I am not sure what is happening exactly... Is there any way I could debug this problem?
Any help would be appreciated...
Without more information about the exception you receive I can only guess what could go wrong: I guess it's because you're using Linq on uninitialized collections in MapFrom. Try implementing a ValueResolver instead.
I get an cast exception when i am trying to insert an entity in Entity Framework (using code-first).
The cast exception is like "impossible to cast ...Collection'1(Entity) to type (Entity)"
From this code :
public virtual T Insert(T entity)
{
return Context.Set<T>().Add(entity);
}
I can't figure out why. I am pretty sure ive done everything right.
Post entity
public class Post
{
public long PostId { get; private set; }
public DateTime date { get; set; }
[Required]
public string Subject { get; set; }
public User User { get; set; }
public Category Category { get; set; }
[Required]
public string Body { get; set; }
public virtual ICollection<Tag> Tags { get; private set; }
public Post()
{
Category = new Category();
if (Tags == null)
Tags = new Collection<Tag>();
}
public void AttachTag(string name, User user)
{
if (Tags.Count(x => x.Name == name) == 0)
Tags.Add(new Tag {
Name = name,
User = user
});
else
throw new Exception("Tag with specified name is already attached to this post.");
}
public Tag DeleteTag(string name)
{
Tag tag = Tags.Single(x => x.Name == name);
Tags.Remove(tag);
return tag;
}
public bool HasTags()
{
return (Tags.Count > 0);
}
}
Tag entity
public class Tag
{
public long TagId { get; private set; }
public string Name { get; set; }
// Qui a ajouté le tag ?
public User User { get; set; }
}
Mapping
public class PostMap: EntityTypeConfiguration<Post>
{
public PostMap()
{
ToTable("Posts");
HasKey(x => x.PostId);
Property(x => x.Subject)
.HasColumnType("varchar")
.HasMaxLength(256)
.IsRequired();
Property(x => x.Body)
.HasColumnType("text")
.IsRequired();
HasMany(x => x.Tags);
HasOptional(x => x.Tags);
}
}
class TagMap : EntityTypeConfiguration<Tag>
{
public TagMap()
{
ToTable("Tags");
HasKey(x => x.TagId);
Property(x => x.Name)
.HasColumnType("varchar")
.HasMaxLength(256)
.IsRequired();
HasRequired(x => x.User);
}
}
Thanks a lots.
Please make sure that you have passed a single element to the Insert method, not a collection containing a single element.
I found the solution.
Here the correct mapping scenario for Post :
public PostMap()
{
ToTable("Posts");
HasKey(x => x.PostId);
Property(x => x.Subject)
.HasColumnType("varchar")
.HasMaxLength(256)
.IsRequired();
Property(x => x.Body)
.HasColumnType("text")
.IsRequired();
HasRequired(x => x.User);
HasMany(x => x.Tags).WithOptional();
}
It is important to specify the the Tags collection is optional. Which is the case in this scenario. A Post can have zero tags attached to it.
HasMany(x => x.Tags).WithOptional();