I can not to seed "IsTerminated" - entity

Why "IsTerminated" data do not set in database?
Everything else are good.
Without this condition working fine.
map.Requires("IsTerminated").HasValue(false)
}).Ignore(m => m.IsTerminated)"
Condition metod
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Employee>()
.Map(map =>
{
map.Properties(p => new
{
p.Id,
p.Name,
p.Salary,
//p.IsTerminated,
p.DepartmentId
});
map.Requires("IsTerminated").HasValue(false);
map.ToTable("tblEmployees");
}).Ignore(m => m.IsTerminated)
.Map(map =>
{
map.Properties(p => new
{
p.Id,
p.Email,
p.Mobile
});
map.ToTable("EmployeeContactDetails");
});
base.OnModelCreating(modelBuilder);
}
Seed metod
protected override void Seed(EmployeeDBContext context)
{
Department department1 = new Department()
{
Name = "Sales",
Employees = new List<Employee>()
{
new Employee()
{
Name = "Mantas",
Salary = 60000,
Email = "Mantas#gmail.com",
Mobile = "+37061433005",
IsTerminated = true
},
new Employee()
{
Name = "Gediminas",
Salary = 40000,
Email = "Gediminas#gmail.com",
Mobile = "+37061433004",
IsTerminated = false
}
}
};
context.Departments.Add(department1);
base.Seed(context);
}
Looks like this is not big problem, but i can not figure out why seeding stops working when i add some condition to code.

Related

SQLite error "near "#gmail": syntax error "flutter

Here's the error I get:
E/SQLiteLog(25090): (1) near "#gmail": syntax error .
It seems like there is a problem in email input.
I guess there is nothing wrong in the creating of database.
creating db:
class UsersTable {
static const String tableName = 'Users';
static const String id = 'id';
static const String email = 'email';
static const String createQuery = '''
CREATE TABLE IF NOT EXISTS $tableName (
$id integer primary key autoincrement,
$email text not null unique);''';
}
in model class:
class Users {
late final int id;
late String email;
Users({
required this.id,
required this.email,
});
Users.fromDb(Map<String, dynamic> map) {
id = map[UsersTable.id];
email = map[UsersTable.email];
}
}
in UserService class which I think is where the problem arise:
class UserService {
...
Future<Users> getOrCreateUser({
required String email,
bool setAsCurrentUser = true,
}) async {
try {
//we found the user
final user = await getUser(email: email);
if (setAsCurrentUser) {
_user = user;
}
return user;
} on CouldNotFindUser {
//we didn't find the user
final createdUser = await createUser(email: email);
if (setAsCurrentUser) {
_user = createdUser;
}
return createdUser;
} catch (e) {
rethrow;
}
}
Future<Users> getUser({required String email}) async {
await _ensureDbIsOpen();
final db = _getDatabaseOrThrow();
final results = await db.query(
UsersTable.tableName,
limit: 1,
where: 'email = ?',
whereArgs: [email.toLowerCase()],
);
if (results.isEmpty) {
throw CouldNotFindUser();
} else {
return Users.fromDb(results.first);
}
}
...}
in main class:
...
Widget build(BuildContext context) {
return FutureBuilder(
future: _userService.getOrCreateUser(email: userEmail),
builder: (context, snapshot) {
return Provider(
create: (ctx) => HomePageController(),
dispose: (ctx, HomePageController controller) =>
...
how can I solve this error?

Property not found in \Illuminate\Contracts\Auth\Authenticatable|nul

Hello I use laravel 8 and backpack 4.1. I get an error: Property not found in \Illuminate\Contracts\Auth\Authenticatable|null, I have user_id in the table 'tenants'. Has somebody an idea, why the variable $ccu is null.
User.php:
public static function getUser()
{
return Auth::guard('backpack')->user();
}
public function tenant(): BelongsTo
{
return $this->belongsTo(Tenant::class);
}
Tenant.php:
vpublic function ccus(): HasMany
{
return $this->hasMany(Ccu::class);
}
public function users():hasMany
{
return $this->hasMany(User::class, 'user_id');
}
DashboardUserController:
public function index()
{
if (backpack_user()->hasRole('admin')) {
$this->data['title'] = trans('backpack::base.dashboard');
$this->data['breadcrumbs'] = [
trans('backpack::crud.admin') => backpack_url('dashboard'),
trans('backpack::base.dashboard') => false,
];
return view('dashboard', $this->data);
} else {
$user=User::getUser();
$ccu = $user->tenant->ccus()->get();
$ccuDiagram = new CcuDiagram($ccu);
$dataForGauge = CcuDiagram::getData($ccu);
$service = Service::find(1);
return view('ccu', ["dataForGauge" => $dataForGauge, "service" => $service]);
}
}
Ccu.php
public function tenant(): HasOne
{
return $this->hasOne(Tenant::Class);
}

Populating Nested List<> in MVC4 C#

I've got a problem populating nested List<>
The object graph looks like this:
Route ⇒ Section ⇒ Co-ordinates
Whenever I try to populate Сoordinates list it just overwrites previous record and at the end gives me only the last Coordinate record. But I want all the Co-ordinates.
Here is my controller code:
List<RequestRouteDataClass> result = new List<RequestRouteDataClass> {
new RequestRouteDataClass() {
RouteRequestId = objRouteManagement.RouteRequestId,
RouteName = objRouteManagement.RouteName,
RouteDescription = objRouteManagement.RouteDescription,
RouteSections = new List<RouteSections> {
new RouteSections() {
Route_Sections_Id = objSections.Route_Sections_Id,
Section_Speed = objSections.Section_Speed,
Section_Description = objSections.Section_Description,
RouteCordinatesSections = new List<SectionCoordinatesRelationData> {
new SectionCoordinatesRelationData() {
SectionCoordinate_Relat_Id = objSectionsCordinates.SectionCoordinate_Relat_Id,
CoordinateLat = objSectionsCordinates.CoordinateLat,
CoordinateLag = objSectionsCordinates.CoordinateLag
}
}
}
}
}
If you want to use Nested List.
Your Model Contains =>
public class MainModelToUse
{
public MainModelToUse()
{
FirstListObject = new List<FirstListClass>();
}
public List<FirstListClass> FirstListObject { get; set; }
}
public class FirstListClass
{
public FirstListClass()
{
SecondListObject = new List<SecondListClass>();
}
public List<SecondListClass> SecondListObject { get; set; }
}
public class SecondListClass
{
public SecondListClass()
{
ThirdListObject = new List<ThirdListClass>();
}
public List<ThirdListClass> ThirdListObject { get; set; }
}
public class ThirdListClass
{
}
Your Code to Nested List =>
FirstListClass vmFirstClassMenu = new FirstListClass();
vmFirstClassMenu.SecondListClass = new List<SecondListClass>();
FirstListClass vmFirstClassCategory = new FirstListClass();
var dataObject1 = //Get Data By Query In Object;
foreach (Model objModel in dataObject1)
{
vmFirstClassCategory = new FirstListClass
{
//Your Items
};
var DataObject2 = //Get Data By Query In Object;
vmFirstClassCategory.SecondListClass = new List<SecondListClass>();
foreach (SecondListClass menuItem in DataObject2)
{
SecondListClass vmFirstClassMenuItem = new SecondListClass
{
//Your Items
};
var DataObject3 = //Get Data By Query In Object;
vmFirstClassMenuItem.ThirdListClass = new List<ThirdListClass>();
foreach (ThirdListClass price in DataObject3)
{
ThirdListClass vmThirdClassobj = new ThirdListClass
{
//Your Items
};
vmFirstClassMenuItem.ThirdListClass.Add(vmThirdClassobj);
}
vmFirstClassCategory.SecondListClass.Add(vmFirstClassMenuItem);
}
}
Hope this is what you are looking for.
First off: spacing helps with readability (edit: but I see you fixed that in your question already):
List<RequestRouteDataClass> result = new List<RequestRouteDataClass>
{
new RequestRouteDataClass()
{
RouteRequestId = objRouteManagement.RouteRequestId,
RouteName = objRouteManagement.RouteName,
RouteDescription = objRouteManagement.RouteDescription,
RouteSections = new List<RouteSections>
{
new RouteSections()
{
Route_Sections_Id = objSections.Route_Sections_Id,
Section_Speed = objSections.Section_Speed,
Section_Description = objSections.Section_Description,
RouteCordinatesSections = new List<SectionCoordinatesRelationData>
{
new SectionCoordinatesRelationData()
{
SectionCoordinate_Relat_Id = objSectionsCordinates.SectionCoordinate_Relat_Id,
CoordinateLat = objSectionsCordinates.CoordinateLat,
CoordinateLag =objSectionsCordinates.CoordinateLag
}
}
}
}
}
};
Next: what you are doing with the above is initiating your lists with a single element in each list. If you want more elements, you have to add them. I recommend using a foreach and the Add() functionality to fill your lists.
From your example it is not clear how your source data is stored, but if you have multiples of something I would expect those too to be in a list or an array of some kind.

nHibernate ByCode Mapping - How to map ManyToMany entirely by convention?

I have defined this mapping:
public class Mapping : ConventionModelMapper
{
public Mapping()
{
IsRootEntity((type, declared) =>
{
return !type.IsAbstract &&
new[] { typeof(Entity<Guid>), typeof(CommonEntity) }.Contains(type.BaseType);
});
IsEntity((x, y) => typeof(Entity<Guid>).IsAssignableFrom(x) && !x.IsAbstract && !x.IsInterface);
IsSet((mi, wasDeclared) =>
{
var propertyType = mi.GetPropertyOrFieldType();
return propertyType.IsGenericType && typeof(System.Collections.Generic.ISet<>).IsAssignableFrom(propertyType.GetGenericTypeDefinition());
});
IsManyToMany((mi, wasDeclared) =>
{
var propertyType = mi.GetPropertyOrFieldType();
var containingType = mi.ReflectedType;
if (typeof(System.Collections.Generic.ISet<>).IsAssignableFrom(propertyType.GetGenericTypeDefinition()))
{
var referenceType = propertyType.GetGenericArguments()[0];
return true;
return !referenceType.GetProperties(BindingFlags.Instance | BindingFlags.Public).Any(p => p.PropertyType.IsAssignableFrom(containingType));
}
return false;
});
Class<Entity<Guid>>(x =>
{
x.Id(c => c.Id, m => m.Generator(Generators.GuidComb));
x.Version(c => c.Version, (vm) => { });
});
BeforeMapClass += OnBeforeMapClass;
BeforeMapManyToOne += OnBeforeMapManyToOne;
BeforeMapSet += OnBeforeMapSet;
BeforeMapManyToMany += OnBeforeMapManyToMany;
Class<CommonEntity>(x =>
{
x.Property(c => c.DateCreated, m => m.Type<UtcDateTimeType>());
x.Property(c => c.DateModified, m => m.Type<UtcDateTimeType>());
});
}
private void OnBeforeMapManyToMany(IModelInspector modelInspector, PropertyPath member, IManyToManyMapper collectionRelationManyToManyCustomizer)
{
collectionRelationManyToManyCustomizer.Column(member.LocalMember.GetPropertyOrFieldType().GetGenericArguments()[0].Name + "Id");
}
private void OnBeforeMapSet(IModelInspector modelInspector, PropertyPath member, ISetPropertiesMapper propertyCustomizer)
{
propertyCustomizer.Key(k=>k.Column(member.GetContainerEntity(modelInspector).Name + "Id"));
propertyCustomizer.Cascade(Cascade.Persist);
if (modelInspector.IsManyToMany(member.LocalMember))
{
propertyCustomizer.Table(member.GetContainerEntity(modelInspector).Name +
member.LocalMember.GetPropertyOrFieldType().GetGenericArguments()[0].Name);
}
}
private void OnBeforeMapManyToOne(IModelInspector modelInspector, PropertyPath member, IManyToOneMapper propertyCustomizer)
{
propertyCustomizer.Column(member.LocalMember.Name + "Id");
}
private void OnBeforeMapClass(IModelInspector modelInspector, Type type, IClassAttributesMapper classCustomizer)
{
classCustomizer.Table('['+ type.Name + ']');
}
}
An I am having a problem with a many to many relationship. I have User, UserPermission and Permission. When I am saving a user after attaching a Permission to it it generates this SQL:
exec sp_executesql N'UPDATE [Permission] SET UserId = #p0 WHERE Id = #p1',N'#p0 uniqueidentifier,#p1 uniqueidentifier',#p0='57A2CD87-4A79-4131-B9CE-A1060168D520',#p1='9D99D340-1B63-4291-B55A-6127A8F34FC9'
When it should be like:
exec sp_executesql N'INSERT INTO UserPermission (UserId, PermissionId) VALUES (#p0, #p1)',N'#p0 uniqueidentifier,#p1 uniqueidentifier',#p0='2C670A01-C2E6-46A3-A412-A1060168F976',#p1='9D99D340-1B63-4291-B55A-6127A8F34FC9'
When I add a specific class mapping for User:
Class<User>(classMapper =>
{
classMapper.Set(x => x.Permissions, map =>
{
//map.Key(k => k.Column("UserId"));
//map.Table("UserPermission");
}, r => r.ManyToMany(m => {}));
});
I can leave out the key and table definition and include the ManyToMany without the column call and it works. But it does the same same thing as my BeforeManyToMany event handler. If I drop the whole Class thing the BeforeMapManyToMany event is not fired and nHibernate thinks I've got a UserId on my Permission table.
Heres User:
public class User : CommonEntity
{
protected User()
{
Permissions = new HashSet<Permission>();
}
public User(User createdBy) : base(createdBy)
{
Permissions = new HashSet<Permission>();
}
public ISet<Permission> Permissions { get; protected set; }
}
After poking around in the source code I realised the problem was that IsOneToMany was checked against the property when defining the set before IsManyToMany. I just needed to define IsOneToMany and it worked without any explicit mappings.
IsOneToMany((mi, wasDeclared) =>
{
var propertyType = mi.GetPropertyOrFieldType();
return ModelInspector.IsEntity(propertyType);
});

Why is NHibernate ignoring FetchMode.Join?

I have an entity called Member. A Member can follow many other Members (according to the domain), thus pertaining a many-to-many relationship. I've created a relationship table (member_follows) in my database. Using Fluent NHibernate I've also dedicated a new entity "MemberFollow" to map this relationship as seen below:
public class MemberMap : MapBase<Member>
{
public MemberMap()
: base()
{
Table("members");
Map(x => x.Id ).Column("id" );
Map(x => x.Fullname).Column("fullname");
}
public class MemberFollowMap : MapBase<MemberFollow>
{
public MemberFollowMap()
: base()
{
Table("members_follows");
Map(x => x.Id).Column("id");
References<Member>(x => x.Follower)
.Column("follower_id")
.Fetch.Join();
References<Member>(x => x.Member)
.Column("member_id");
.Fetch.Join();
}
}
Since the FetchMode for MemberFollow mapping is set to Join, I was expecting this query to fetch the members in one query. However when I look at the logs, I see that NHibernate performs a simple select to find the Ids of each followed member and upon access, loads members one by one.
public IList<Member> ListFollowings(Int32 FollwerId, Int32 Start, Int32 Size, String SortBy, SortOrder OrderBy)
{
DetachedCriteria Filter = DetachedCriteria.For<MemberFollow>();
Filter.Add (Expression.Eq("Follower.Id", FollwerId));
Filter.AddOrder (OrderBy == SortOrder.Asc ? Order.Asc(SortBy) : Order.Desc(SortBy));
Filter.SetProjection (Projections.Property("Member"));
Filter.SetFirstResult(Start);
Filter.SetMaxResults (Size );
return Find<Member>(Filter);
}
So my question is: Why is NHibernate ignoring the FetchMode set by the mapping class?
I think you may take it from the wrong angle. In NHibernate, it is quite unusual to explicitly map a many-to-many relationship as a model object. See below a proposal for changes.
Given the domain object MyMember and its overriden mapping:
public class MyMember : DomainObjectBase
{
public virtual string Name { get; set; }
public virtual IList<MyMember> Follows { get; set; }
}
public class MemberOverride : IAutoMappingOverride<MyMember>
{
public void Override(AutoMapping mapping)
{
mapping.HasManyToMany<MyMember> (x => x.Follows)
.Table("FollowMap")
.ParentKeyColumn("FollowerID")
.ChildKeyColumn("FollowedID")
.Cascade.SaveUpdate(); ;
}
}
The following test pass:
[Test]
public void WhoFollowsWho()
{
var a = new MyMember {Name = "A"};
var b = new MyMember {Name = "B"};
var c = new MyMember {Name = "C"};
var d = new MyMember {Name = "D"};
var e = new MyMember {Name = "E"};
a.Follows = new List<MyMember> { b, c, d, e };
d.Follows = new List<MyMember> { a, c, e };
using (var t = Session.BeginTransaction())
{
Session.Save(a);
Session.Save(b);
Session.Save(c);
Session.Save(d);
Session.Save(e);
t.Commit();
}
using (var t = Session.BeginTransaction())
{
DetachedCriteria followersOfC = DetachedCriteria.For<MyMember>();
followersOfC.CreateCriteria("Follows")
.Add(Expression.Eq("Id", c.Id))
.SetProjection(Projections.Property("Name"));
var results = followersOfC.GetExecutableCriteria(Session).List();
t.Commit();
CollectionAssert.AreEquivalent(new[]{"A", "D"}, results);
}
using (var t = Session.BeginTransaction())
{
DetachedCriteria followedByA = DetachedCriteria.For<MyMember>();
followedByA.CreateAlias("Follows", "f")
.Add(Expression.Eq("Id", a.Id))
.SetProjection(Projections.Property("f.Name"));
var results = followedByA.GetExecutableCriteria(Session).List();
t.Commit();
CollectionAssert.AreEquivalent(new[]{"B", "C", "D", "E"}, results);
}
}
And the produced SQL relies, as expected, on inner joins:
NHibernate:
SELECT this_.Name as y0_ FROM "MyMember" this_
inner join FollowMap follows3_ on this_.Id=follows3_.FollowerID
inner join "MyMember" mymember1_ on follows3_.FollowedID=mymember1_.Id
WHERE mymember1_.Id = #p0
NHibernate:
SELECT f1_.Name as y0_ FROM "MyMember" this_
inner join FollowMap follows3_ on this_.Id=follows3_.FollowerID
inner join "MyMember" f1_ on follows3_.FollowedID=f1_.Id
WHERE this_.Id = #p0
Note: If, instead of only retrieving the "Name" property of each MyMember, you retrieve the full instances of MyMember, the SQL statement keeps the same shape. Only additional projections are added to the SELECT clause. However, you'll have to fix the test to make it pass again ;-)
Note 2: Provided you're willing to deal with a many-to-many relationship which holds properties of its own, this post from Kyle Baley and this one from the Nhibernate blog may provide some help on this subject.
Note 3: I've given it a try :-)
Given the domain objects MySecondMember and MyFollowMap and their overriden mapping:
public class MySecondMember : DomainObjectBase
{
public virtual string Name { get; set; }
public virtual IList<MyFollowMap> Follows { get; set; }
}
public class MyFollowMap : DomainObjectBase
{
public virtual MySecondMember Who { get; set; }
public virtual DateTime StartedToFollowOn { get; set; }
}
public class MemberSecondOverride : IAutoMappingOverride<MySecondMember>
{
public void Override(AutoMapping mapping)
{
mapping.HasMany(x => x.Follows);
}
}
The following test pass:
[Test]
public void WhoFollowsWho2()
{
var a = new MySecondMember { Name = "A" };
var b = new MySecondMember { Name = "B" };
var c = new MySecondMember { Name = "C" };
var d = new MySecondMember { Name = "D" };
var e = new MySecondMember { Name = "E" };
var bfm = new MyFollowMap { Who = b, StartedToFollowOn = DateTime.UtcNow };
var cfm = new MyFollowMap { Who = c, StartedToFollowOn = DateTime.UtcNow };
var dfm = new MyFollowMap { Who = d, StartedToFollowOn = DateTime.UtcNow };
var efm = new MyFollowMap { Who = e, StartedToFollowOn = DateTime.UtcNow };
a.Follows = new List { bfm, cfm, dfm, efm };
var afm = new MyFollowMap { Who = a, StartedToFollowOn = DateTime.UtcNow };
cfm = new MyFollowMap { Who = c, StartedToFollowOn = DateTime.UtcNow };
efm = new MyFollowMap { Who = e, StartedToFollowOn = DateTime.UtcNow };
d.Follows = new List { afm, cfm, efm };
using (var t = Session.BeginTransaction())
{
Session.Save(a);
Session.Save(b);
Session.Save(c);
Session.Save(d);
Session.Save(e);
t.Commit();
}
using (var t = Session.BeginTransaction())
{
DetachedCriteria followersOfC = DetachedCriteria.For<MySecondMember>();
followersOfC.CreateAlias("Follows", "f")
.CreateAlias("f.Who", "w")
.Add(Expression.Eq("w.Id", c.Id))
.SetProjection(Projections.Property("Name"));
var results = followersOfC.GetExecutableCriteria(Session).List();
t.Commit();
CollectionAssert.AreEquivalent(new[] { "A", "D" }, results);
}
using (var t = Session.BeginTransaction())
{
DetachedCriteria followedByA = DetachedCriteria.For<MySecondMember>();
followedByA
.CreateAlias("Follows", "f")
.CreateAlias("f.Who", "w")
.Add(Expression.Eq("Id", a.Id))
.SetProjection(Projections.Property("w.Name"));
var results = followedByA.GetExecutableCriteria(Session).List();
t.Commit();
CollectionAssert.AreEquivalent(new[] { "B", "C", "D", "E" }, results);
}
}
And the produced SQL relies, as expected, on inner joins:
NHibernate:
SELECT this_.Name as y0_ FROM "MySecondMember" this_
inner join "MyFollowMap" f1_ on this_.Id=f1_.MySecondMember_id
inner join "MySecondMember" w2_ on f1_.Who_id=w2_.Id
WHERE w2_.Id = #p0;
NHibernate:
SELECT w2_.Name as y0_ FROM "MySecondMember" this_
inner join "MyFollowMap" f1_ on this_.Id=f1_.MySecondMember_id
inner join "MySecondMember" w2_ on f1_.Who_id=w2_.Id
WHERE this_.Id = #p0