Fluent-NHibernate added Multiple Data To Database MVC - asp.net-mvc

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

Related

Fluent NHibernate Mapping Doesn't Work For Some Tables

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.

Linq-To-Nhibernate multiples joins with conditionals

I'm using Fluent-Nhibernate version 1.3 and I'm trying to make a query envolving 5 tables. I created a sql query for an oracle database and I'm trying to replicate with linq-to-nhibernate.
Following a sample of my entities and mapping.
Entities:
public class A
{
public virtual int idA { get; set; }
public virtual String codA { get; set; }
public virtual String tipoA { get; set; }
public virtual IList<B> listB { get; set; }
}
public class B
{
public virtual C objectC { get; set; }
public virtual A objectA { get; set; }
public virtual DateTime dtBegin { get; set; }
public virtual DateTime dtEnd { get; set; }
}
public class C
{
public virtual int idC { get; set; }
public virtual String codeC { get; set; }
public virtual IList<B> listB { get; set; }
public virtual IList<D> listD { get; set; }
}
public class D
{
public virtual C objectC { get; set; }
public virtual string flgD { get; set; }
public virtual DateTime dtBegin { get; set; }
public virtual DateTime dtEnd { get; set; }
public virtual E objectE { get; set; }
}
public class E
{
public virtual int idE { get; set; }
public virtual String dsE { get; set; }
public virtual DateTime dtBegin { get; set; }
public virtual DateTime dtEnd { get; set; }
public virtual IList<D> listD { get; set; }
}
My mapping:
class AMap : ClassMap<A>
{
public AMap()
{
Table("A");
Id(x => x.idA, "ID_A").GeneratedBy.Sequence("StringA");
Map(x => x.tipoA, "TP_A");
Map(x => x.codA, "CODE_A");
HasMany(x => x.listB).Cascade.All().KeyColumn("ID_A");
}
}
class BMap : ClassMap<B>
{
public BMap()
{
Table("B");
CompositeId()
.KeyReference(x => x.objectC, "ID_C")
.KeyReference(x => x.objectA, "ID_A")
.KeyProperty(x => x.dtBegin, "DT_BEGIN");
Map(x => x.dtEnd, "DT_END");
}
}
class CMap : ClassMap<C>
{
public CMap()
{
Table("C");
Id(x => x.idC, "ID_C").GeneratedBy.Sequence("StringC");
Map(x => x.codeC, "CODE_C");
HasMany(x => x.listB).Cascade.All().KeyColumn("ID_C");
HasMany(x => x.listD).Cascade.All().KeyColumn("ID_D");
}
}
class DMap : ClassMap<D>
{
public DMap()
{
Table("D");
CompositeId()
.KeyReference(x => x.objectC, "ID_C")
.KeyProperty(x => x.flgD, "FLG_D")
.KeyProperty(x => x.dtBegin, "DT_BEGIN");
References(x => x.objectE, "CODE_E");
Map(x => x.dtEnd, "DT_END");
}
}
class EMap : ClassMap<E>
{
public EMap()
{
Table("E");
Id(i => i.idE, "ID_E").GeneratedBy.Assigned();
Map(m => m.dsE, "DSC_E");
Map(m => m.dtBegin, "DT_BEGIN");
Map(m => m.dtEnd, "DT_END");
HasMany(x => x.listD).Cascade.All().KeyColumn("ID_E");
}
}
My SQL Query(it works):
SELECT C.CODE_C, E.CODE_E, E.DT_BEGIN
FROM TABLEA A, TABLEB B, TABLEC C, TABLED D, TABLEE E
WHERE A.CODE_A = '0000' AND A.ID_A = B.ID_A AND B.ID_C = C.ID_C AND B.DT_END IS NULL
AND C.ID_C = D.ID_C AND D.DT_END IS NULL AND D.CODE_E = E.CODE_E AND E.DT_END IS NULL;
I tried to use multiple join but then some relathionship are collections so I would have to make a where inside the join.
So my question is: is possible to make this same Sql query as linq-to-nhibernate or is better to make a sequence of selects? And no i can't change the database.
Thanks in advance.
the is null query is only possible using DateTime? as type
var query = from b in B
from c in b.C
from d in c.listD
from e in d.E
where b.A.Code == "0000" && b.EndDate == null & ...
select new { Ccode = c.Code, Ecode = e.Code, E_BeginDate = e.BeginDate }
Update: to answer the third comment
grouping the results has to be done in memory because grouping in sql can only return aggregations
var results = query.AsEnumerable()
.GroupBy(a => a.Ccode, a => a.Ecode, (key, values) => new { Ccode = Key, Ecodes = values.ToList() })
.List();

Mapping one (entity class) to many (dto's/viewModels)

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.

Cast exception error when i am trying to insert an entity in Entity Framework (using code-first)

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();

NCommon 1.1 and EF4

I am new to NCommon and am looking for an example project to get started.
I am using EF4.
I assume one needs to use EF4 with POCOs?
Thanks for any help.
NCommon.Configure.Using(new StructureMapContainerAdapter(ObjectFactory.Container))
.ConfigureState<DefaultStateConfiguration>()
.ConfigureData<EFConfiguration>(config => config.WithObjectContext(
() =>
{
SiteContext db = new SiteContext(ConfigurationManager.ConnectionStrings["TestTheBest"].ConnectionString);
if (Transaction.Current != null )
{
db.Context.Connection.Open();
}
return db.Context;
}))
.ConfigureUnitOfWork<DefaultUnitOfWorkConfiguration>(config => config.AutoCompleteScope());
public class SiteContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<Company> Companies { get; set; }
public DbSet<Comment> Comments { get; set; }
public DbSet<Category> Categories { get; set; }
public DbSet<Test> Tests { get; set; }
public DbSet<Client> Clients { get; set; }
public DbSet<Question> Questions { get; set; }
public DbSet<Section> Sections { get; set; }
public DbSet<Answer> Answers { get; set; }
public DbSet<GlobalSettings> GlobalSettings { get; set; }
public DbSet<PassageTest> PassageTest { get; set; }
public DbSet<PassageTestAnswer> PassageTestAnswer { get; set; }
public DbSet<SaaSUser> SaaSUser { get; set; }
public SiteContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
Context.SavingChanges += new EventHandler(Context_SavingChanges);
}
void Context_SavingChanges(object sender, EventArgs e)
{
if(Context.Connection.State==ConnectionState.Open)
Context.Connection.Close();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasMany(x => x.Invitations).WithRequired(x=>x.user).WillCascadeOnDelete(true);
modelBuilder.Entity<User>().HasMany(x => x.PassageTests).WithRequired(x => x.user).WillCascadeOnDelete(true);
modelBuilder.Entity<PassageTest>().HasMany(x => x.PassageTestAnswers).WithRequired(x => x.passageTest).WillCascadeOnDelete(true);
// modelBuilder.Entity<Company>().HasMany(x => x.Users).WithRequired(x => x.company).WillCascadeOnDelete(true);
modelBuilder.Entity<Question>().HasMany(x => x.Answers).WithRequired(x => x.question).WillCascadeOnDelete(true);
modelBuilder.Entity<Question>().HasMany(x => x.PassageTestAnswers).WithRequired(x => x.question).WillCascadeOnDelete(true);
modelBuilder.Entity<Test>().HasMany(x => x.Invitations).WithRequired(x => x.test).WillCascadeOnDelete(true);
modelBuilder.Entity<Test>().HasMany(x => x.PassageTests).WithRequired(x => x.test).WillCascadeOnDelete(true);
modelBuilder.Entity<Test>().HasMany(x => x.Sections).WithRequired(x => x.test).WillCascadeOnDelete(true);
modelBuilder.Entity<Client>().HasMany(x => x.Tests).WithRequired(x => x.client).WillCascadeOnDelete(true);
}
public ObjectContext Context
{
get { return ((IObjectContextAdapter)this).ObjectContext; }
}
}

Resources