I'm following this blog post to learn the new SimpleMemberProvider and SimpleRoleProvider features in latest release of asp.net MVC.
Instead of calling "UserId", I named it just "Id". Then, however, when I enabled the "SimpleRoleProvider" in web.config, I got error like "Foreign key 'fk_UserId' references invalid table 'MemberProfile'." it seems by default it's looking for UserId column to create foreign key constraint.
Is it possible to user something else rather than "UserId"?
I believe it gets it's name from it's initialization
Look for Filters
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
Related
I'm new in programming and I've built projects on xampp. There I created the databases in SQL (MARIADB) in 2 separated files (DML and DDL).
Now, learning Symfony I found that looks like I must use ORM to create the database. Can't I just create DML and DDL and connect/upload them to Symfony instead of using ORM?
I've been 2 days looking for information on how to do that, and I've just found ORM documentation. I wish I just could do something like this function:
function mod001_conectoBD () {
$address= "localhost";
$user= "root";
$password= "";
$database = "projectDDL"; //(which I uploaded on phpmyadmin as projectDDL.sql)
$link = mysqli_connect( $address, $user, $password, $database );
if ( !$link ) {
echo "Fail connection";
}
return $link;
}
function mod001_disconnectBD ( $link ) {
mysqli_close( $link );
}
This ofc is just the example i used on my xampp project. With this I just used the uploaded projectDDL.sql and built the app around it. Thanks and sorry for my ignorance in this matter.
The reason why I want this is building composite Primary keys, and editting id names, which i find so difficult on symfony.
Imagine for example a table that requires 3 foreign keys and its own id to have a 4 fields primary key, dont know how to make that possible in Symfony.
to connect symfony to mariadb you must modify the .env file which is at the root of your project, for your case it will give something like this:
DATABASE_URL="mysql://root#127.0.0.1:3306/projectDDL"
symfony takes care of creating the database for you, and for each table you have to create an entity
you can create your database with this command on the shell:
php bin/console doctrine:database:create
if you want to create a primary key made up of several foreign keys, doctirne allows you to do that I have already used in a project, you create an entity with foreign keys from your tables and you specify at the beginning that it is also an ID, ex :
#[Id, ManyToOne(targetEntity: User::class)]
#[Id, ManyToOne(targetEntity: Comment::class)]
#[Id, ManyToOne(targetEntity: Video::class)]
Documentation:
https://www.doctrine-project.org/projects/doctrine-orm/en/2.14/tutorials/composite-primary-keys.html#use-case-1-dynamic-attributes
I have a asp net core 3.1 web application. We use repository pattern with entity framework.
services.AddDbContext<MyDbContext>(options => options.UseSqlServer(_configuration.GetConnectionString("MyConnString")), ServiceLifetime.Scoped);
Made up scenario, just bec everybody knows the "Customer-orders"-scenario:
When I create a new Order and want to connect it to an existing Customer I write something like this. Works ok.
var order = new Order(){...}
order.Customer = _dbContext.Customers.FirstOrDefault(c=>c.CustomerId = 42);
_dbContext.Orders.Add(order);
_dbContext.SaveChanges();
However. For other reasons we need to have dbContext transient, initiated like below:
services.AddDbContext<MyDbContext>(options => options.UseSqlServer(_configuration.GetConnectionString("MyConnString")), ServiceLifetime.Transient);
This makes the code above fail. Error message is the Customer is already attached to dbContext ("The instance of entity type 'Customer' cannot be tracked because another instance with the same key value for {'CustomerId'} is already being tracked. When attaching existing entities, , ensure that only one entity instance with a given key value is attached")
or, if I test setting order.Customer = null:
The error message says "cant insert Id on identity column" (which it shouldnt, the customer already exists). ("Cannot insert explicit value for identity column in table 'Users' when IDENTITY_INSERT is set to OFF.")
In OpenERP7, the core module account has a declaration for account.invoice which has, at some point, the following declaration:
addons/account/account_invoice.py:343
_sql_constraints = [
('number_uniq', 'unique(number, company_id, journal_id, type)', 'Invoice Number must be unique per Company!'),
]
In a module which redefined account.invoice I wanted to remove the constraint with two different approaches:
Removing it in init (account_invoice::init(self, pool, cr))
def __init__(self, pool, cr):
super(account_invoice, self).__init__(pool, cr)
try:
cr.execute('ALTER TABLE account_invoice DROP CONSTRAINT IF EXISTS account_invoice_number_uniq')
finally:
pass
Replacing the constraint
_sql_constraints = [
('number_uniq', 'check(1=1)', 'Dummy check, always true, used to replace the previous constraint'),
]
However, when I reinstall the module in which those two declarations were made, I get an error (in the PG logs) telling me that the constraint account_invoice_number_uniq could not be craeted for a unique key since there's repeated data.
How can I prevent having such error? How can I prevent the system attempting to create (first; then... replace/delete) the constraint?
Check the Below Reference Link to remove the SQL Constraint Of Parent Class in Odoo
Click To See the Reference For Remove the SQL Constraint In Odoo(formally OpenERP)
I have a User table in my repository pattern database and I am looking to connect the Roles. What is the best way to customize simple membership?
Read the following MSDN articles:
Implementing a Membership Provider
Implementing a Role Provider
and the following CodeProject article:
Custom MembershipProvider and RoleProvider Implementations that use Web Services
You should set your configuration in InitializeSimpleMembershipAttribute.cs file located into the Filters folder of your project.
Open that file and find the following line:
WebSecurity.InitializeDatabaseConnection("DefaultConnection",
"UserProfile",
"UserId",
"UserName",
autoCreateTables: true);
Now, you just need to put your connection string to your database(must be declared into web.config) into the first parameter, table name into the second parameter, UserId column name into the 3th param. and UserName column name into the 4th param.
About the last param, if you set it to true, if simple membership doesn't find any of the required table into your database, it'll create them.
However, I recommend you that you use separate tables for simple membership and let SM create its own tables. After that, you can add all your existing users to the SM tables by a block of code like the following, once for ever:
var oldUsers = db.Users.ToList();
foreach (User u in oldUsers)
{
WebSecurity.CreateUserAndAccount(u.UserName, u.Password);
}
And after that, you haven't problems with the membership and authorization jobs any more...
This is a strange one replicated in the following code:
using (ISession session = RepositoryTestHelper.SessionFactory.OpenSession())
{
//session.BeginTransaction();
UserRepo repo = new UserRepo(session);
CompanyRepo cRepo = new CompanyRepo(session);
var user = repo.FindByEmail("test.user#blah.com");
user.CompanyAssociations.Add(new CompanyUserAssoc()
{
User = user,
Company = cRepo.GetById(1)
});
repo.AddOrUpdate(user);
//session.Transaction.Commit();
}
And the relationship between user, company and CompanyUserAssoc is fairly straight forward:
For the company:
HasMany<CompanyUserAssoc>(x => x.UserAssociations).KeyColumn("User_id");
For the user:
HasMany<CompanyUserAssoc>(x => x.CompanyAssociations).KeyColumn("Company_id")
And for the association class itself:
References(x => x.Company).UniqueKey("CompanyId_UserId");
References(x => x.User).UniqueKey("CompanyId_UserId");
Now this is where I am baffled. Notice in my initial code that the begin and commit trans calls are commented out. This actually means the code will work! The CompanyUserAssoc is created and correctly references the user and the company with id of 1. Great!
But... sadly when I put this in a transaction i get this error:
{"The UPDATE statement conflicted with the FOREIGN KEY constraint \"FK3C47859753A62C6E\". The conflict occurred in database \"xxxx\", table \"dbo.Company\", column 'Id'.\r\nThe statement has been terminated."}
But why? Well that's my question. What i have see in the profiler is that it does this:
exec sp_executesql N'UPDATE [CompanyUserAssoc] SET Company_id = null WHERE Company_id = #p0',N'#p0 int',#p0=1
Wait... what? NULL? Why is it setting the company id to null? and why is it only doing this when in a transaction? What's "wrong" with my Nhibernate mapping?
Since both collections are mapped as non-inverse (the default) and the Company collection has no users, it will issue that update to clear the link table. Could you try setting the UserAssociations to inverse? Or, what I usually do when an explicit link table is involved, is set both HasManys to inverse and simply work with the link table directly.
This was a red herring in the end, a fish I have come to despise. I had not noticed in my haste and dependence on intellisense that the UserAssocations property of the Company was not an IList but an IList! yes I have stupidly chosen the Nhib map class instead of the domain class.. This weirdly didn't error in the way you would expect, and worked without a transaction, but why?
Well - Nhib was able to insert the assoc entry, but then believed it needed to update that same table with the id it had already inserted (because it somehow sees it as a different entity?). I would have expected a compilation error here in the map class itself as I was using the type, but no. And without a transaction the sql generated works.
I would investigate more as to why, but I've answered this just to highlight a rare and silly mistake which can lead to a lot of investigation if missed.