Quantcast
Channel: MySQL Forums - Connector/NET and C#, Mono, .Net
Viewing all articles
Browse latest Browse all 1451

How to do Insert in many-to-many scenario while working with entity framework for mysql? (no replies)

$
0
0
This should be a quite common scenario. Here're the database tables.

CREATE TABLE table1 ( ID int(11) NOT NULL AUTO_INCREMENT, Name varchar(45) DEFAULT NULL, PRIMARY KEY (ID) ) ENGINE=InnoDB DEFAULT CHARSET=utf8

CREATE TABLE table2 ( ID int(11) NOT NULL AUTO_INCREMENT, Name varchar(45) DEFAULT NULL, PRIMARY KEY (ID) ) ENGINE=InnoDB DEFAULT CHARSET=utf8

CREATE TABLE table1_table2 ( ID1 int(11) NOT NULL, ID2 int(11) NOT NULL, KEY fk1_idx (ID1), KEY fk2_idx (ID2), CONSTRAINT fk1 FOREIGN KEY (ID1) REFERENCES table1 (ID) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT fk2 FOREIGN KEY (ID2) REFERENCES table2 (ID) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8

Then here's my Program.cs:

static void Main(string[] args)
{
using (testEntities ctx = new testEntities())
{
table1 t1 = new table1
{
Name = "t1",
table2 = new List<table2>()
};

table2 t2 = new table2
{
Name = "t2"
};

t1.table2.Add(t2);
ctx.table1.Add(t1);

ctx.SaveChanges();
}
}

Quite straightforward snippet. Then I got this annoying exception:

An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types. See the InnerException for details.

A little drill-down got me to some weird sql syntax error:

{"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(SELECT\n `table1_table2`.`ID1`, \n `table1_table2`.`ID2`\n FROM `ta' at line 1"}

Have no idea where in this auto-generated sql has syntax error.

Any clue to help me please? Thanks.
Nico

Viewing all articles
Browse latest Browse all 1451

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>